Else ai aifamily address type afinet or afinet6

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Types •  All values in network byte order (Big Endian) –  htonl(), htons(): host to network, 32 and 16 bits –  ntohl(), ntohs(): network to host, 32 and 16 bits –  Remember to always convert! •  All address types begin with family –  sa_family in sockaddr tells you actual type •  Not all addresses are the same size –  e.g., struct sockaddr_in6 is typically 28 bytes, yet generic struct sockaddr is only 16 bytes –  So most calls require passing around socket length –  New sockaddr_storage is big enough Client Skeleton (IPv4) Client interface struct sockaddr_in { short sin_family; /* = AF_INET */ u_short sin_port; /* = htons (PORT) */ struct in_addr sin_addr; char sin_zero[8]; } sin; int s = socket (AF_INET, SOCK_STREAM, 0); bzero (&sin, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_port = htons (13); /* daytime port */ sin.sin_addr.s_addr = htonl (IP_ADDRESS); connect (s, (sockaddr *) &sin, sizeof (sin)); while ((n = read (s, buf, sizeof (buf))) > 0) write (1, buf, n); Server Skeleton (IPv4) Server interface int s = socket (AF_INET, SOCK_STREAM, 0); struct sockaddr_in sin; bzero (&sin, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_port = htons (9999); sin.sin_addr.s_addr = htonl (INADDR_ANY); bind (s, (struct sockaddr *) &sin, sizeof (sin)); listen (s, 5); for (;;) { socklen_t len = sizeof (sin); int cfd = accept (s, (struct sockaddr *) &sin, &len); /* cfd is new connection; you never read/write s */ do_something_with (cfd); close (cfd); } Looking up a socket address with getaddrinfo struct addrinfo hints, *ai;! int err;! memset (&hints, 0, sizeof (hints)); ! hints.ai_family = AF_UNSPEC; /* or AF_INET or AF_INET6 */! hints.ai_socktype = SOCK_STREAM;/* or SOCK_DGRAM for UDP */! ! err = getaddrinfo ("www.brown.edu", "http", &hints, &ai);! if (err)! fprintf (stderr, "%s\n", gia_strerror (err)); ! else {! /* ai->ai_family = address type (AF_INET or AF_INET6) */! /* ai->ai_addr = actual address cast to (sockaddr *) */ ! /* ai->ai_addrlen = length of actual address */ ! freeaddrinfo (ai); /* must free when done! */! }! getaddrinfo() [RFC3493] •  Protocol- independent node name to ad...
View Full Document

Ask a homework question - tutors are online