c.md (1821B)
1 # c 2 3 * create tcp socket using socket() 4 * establish connection to server using connect() 5 * communicate using send() and recv() 6 * close connection using close() 7 8 using address structure 9 1. sockaddr: generic data type 10 2. in_addr: internet address 11 3. sockaddr_in: another view of sockaddr 12 13 struct sockaddr_in { 14 unsigned short sin_family; // internet protocol (AF_INET) 15 unsigned short sin_port; // address port (16bits) 16 struct in_addr sin_addr; // internet address (32bits) 17 char sin_zero[8]; // not used 18 } 19 20 create a socket 21 22 int socket(int protocolFamily, int type, int protocol) 23 24 - protocolFamily: always PF_INET for tcp/ip sockets 25 - type: type of socket (SOCK_STREAM or SOCK_DGRAM) 26 - protocol: socket protocol (IPPROTO_TCP or IPPROTO_UDP) 27 28 * socket() returns the descriptor of the new socket if no error occurs and -1 otherwise 29 30 example 31 ``` 32 #include <sys/types.h> 33 #include <sys/socket.h> 34 int servSock; 35 if ((servSock= socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))<0) 36 ``` 37 38 39 bind to a socket 40 41 int bind(int socket, struct sockaddr *localAddress, unsigned int addressLength) 42 43 - socket: socket (returned by socket()) 44 - localAddress: populated sockaddr structure describing local address 45 - addressLength: number of bytes in sockaddr structure - usually just size of (localAddress) 46 47 * bind() returns 0 if no error and -1 otherwise 48 49 example 50 ``` 51 struct sockaddr_in ServAddr; 52 ServAddr.sin_family = AF_INET; // internet address family 53 ServAddr.sin_addr.s_addr = htonl(INADDR_ANY); // any incoming interface 54 ServAddr.sin_port = htons(ServPort); // local port 55 56 if (bind(servSock, (struct sockaddr *) &ServAddr, sizeof(echoServAddr))<0) 57 ``` 58 59 /* 60 #include <arpa/inet.h> // defins in_addr structure 61 #include <sys/types.h> // 62 #include <netdb.h> // 63 #include <string.h> // 64 #include <stdlib.h> // 65 #include <unistd.h> // 66 #include <errno.h> // 67 */