DATA TYPES ========== // Socket Address struct sockaddr { unsigned short sa_family; // address family, AF_xxx char sa_data[14]; // 14 bytes of protocol address }; // Socket Address Internet struct sockaddr_in { short int sin_family; // Address family unsigned short int sin_port; // Port number struct in_addr sin_addr; // Internet address unsigned char sin_zero[8]; // Same size as struct sockaddr }; sizeof(sockadd_in) == sizeof(sockaddr) // Internet address (a structure for historical reasons) struct in_addr { unsigned long s_addr; // that's a 32-bit long, or 4 bytes }; CONVERSIONS =========== Byte Order: ---------- htons() -- "Host to Network Short" htonl() -- "Host to Network Long" ntohs() -- "Network to Host Short" ntohl() -- "Network to Host Long" IP to Text: ---------- ina.sin_addr.s_addr = inet_addr("10.12.110.57"); +-> PROBLEM: fail == -1 == (unsigned) -1 == 255.255.255.255 ( broadcast ) if (inet_aton("10.12.110.57", &(my_addr.sin_addr))) printf("error converting address.\n"); +-> PROBLEM: not available in every plataform. printf("address: %s\n", inet_ntoa(my_addr.sin_addr)); FUNCTIONS ========= socket(): Get the file descriptor. bind(): What port am I on? -> Associate a socket with a port. TIP: my_addr.sin_port = htons(0); // choose an unused port at random my_addr.sin_addr.s_addr = htonl(INADDR_ANY); // use my IP address REUSE ADDRESS: int yes=1; // lose the pesky "Address already in use" error message if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) { perror("setsockopt"); exit(1); } DON'T CALL IT: When you don't mind the local port, just remote one, as telnet. connect(): Start the connection. INFO: will call bind() if socket was not binded. listen(): Wait for a connection. INFO: backlog: how many connections will wait before they're accept()'ed. INFO: sequence is socket() -> bind() -> listen() -> accept() accept(): removes the pending connection from queue and assign a new file descriptor to it. INFO: new fd will be ready to send() and recv(). INFO: old fd will still listen to new connections.