Socket Programming in C: Server and Client
Socket Programming in C: Server and Client
Clients
Server user
ports space
Socket programming in C
TCP/UDP TCP/UDP
Socket API kernel
space
IP IP
1
22-Sep-17
• Byte Order
– Different computers may have different internal representation of 16 / 32-
bit integer (called host byte order).
Byte Ordering Functions
– Examples • Converts between host byte order and network byte
• Big-Endian byte order (e.g., used by Motorola 68000): order
– ‘h’ = host byte order
– ‘n’ = network byte order
– ‘l’ = long (4 bytes), converts IP addresses
– ‘s’ = short (2 bytes), converts port numbers
• Little-Endian byte order (e.g., used by Intel 80x86): #include <netinet/in.h>
2
22-Sep-17
• AF_INET: associates a socket with the Internet protocol family Ethernet Adapter
• SOCK_STREAM: selects the TCP protocol
• SOCK_DGRAM: selects the UDP protocol
3
22-Sep-17
4
22-Sep-17
• Used to get service description (typically port number) /* connect: use the Internet address family */
• Returns servent based on name srv.sin_family = AF_INET;
struct hostent *hp; /*ptr to host info for remote*/ /* connect: connect to IP Address “128.2.35.50” */
struct sockaddr_in peeraddr; srv.sin_addr.s_addr = inet_addr(“128.2.35.50”);
char *name = “www.tezu.ernet.in”;
if(connect(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) {
peeraddr.sin_family = AF_INET; perror(”connect"); exit(1);
hp = gethostbyname(name) }
peeraddr.sin_addr.s_addr = ((struct in_addr*)(hp->h_addr))->s_addr;
5
22-Sep-17
6
22-Sep-17
7
22-Sep-17
8
22-Sep-17