The following is an example of the simplest client/server program to learn the socket API.
The function of the SERV.C program is to read the characters from the client and return directly to the back:
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #includ e<stdlib.h> #include <errno.h> #include <arpa/inet.h> #include <netinet/in.h> #include <str
Ing.h> #define ERR_EXIT (m) \ Do {\ perror (m); \ EXIT (exit_failure); \} while (0) int main (void) {int listenfd;//passive socket (file descriptor), which can only accept if (LISTENFD = socket (pf_inet, sock_s
Tream, ipproto_tcp)) < 0)//LISTENFD = socket (af_inet, sock_stream, 0) err_exit ("Socket error");
struct sockaddr_in servaddr;
memset (&servaddr, 0, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
Servaddr.sin_port = htons (5188);
SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); /* servaddr.sin_addr.s_addr = inet_addr ("127.0.0.1"); * * * Inet_aton ("127.0.0.1", &servaddr.sin_addr);
*/int on = 1; if (setsockopt (listeNFD, Sol_socket, so_reuseaddr, &on, sizeof (ON)) < 0) err_exit ("setsockopt error");
if (Bind (LISTENFD, (struct sockaddr *) &servaddr, sizeof (SERVADDR)) < 0) Err_exit ("Bind error");
if (Listen (LISTENFD, Somaxconn) < 0)//listen should be after the socket and bind, but before accept ("Err_exit error"); struct sockaddr_in peeraddr; Outgoing parameter socklen_t peerlen = sizeof (PEERADDR); Incoming outgoing parameter must have an initial value of int conn; Socket connected (to active socket, or active Connect) if ((conn = Accept (LISTENFD, (struct sockaddr *) &peeraddr, &peerlen)) < 0
) Err_exit ("Accept error");
printf ("Recv Connect ip=%s port=%d\n", Inet_ntoa (PEERADDR.SIN_ADDR), Ntohs (Peeraddr.sin_port));
struct sockaddr_in localaddr;
Char serv_ip[20];
socklen_t Local_len = sizeof (LOCALADDR);
memset (&localaddr, 0, sizeof (LOCALADDR)); if (getsockname (conn, struct sockaddr *) &localaddr,&local_len)!= 0) err_exit ("GEtsockname error ");
Inet_ntop (Af_inet, &localaddr.sin_addr, serv_ip, sizeof (SERV_IP));
printf ("Host%s:%d\n", Serv_ip, Ntohs (Localaddr.sin_port));
Char recvbuf[1024];
while (1) {memset (recvbuf, 0, sizeof (RECVBUF));
int ret = READ (conn, recvbuf, sizeof (RECVBUF));
Fputs (Recvbuf, stdout);
Write (conn, recvbuf, ret);
Close (conn);
Close (LISTENFD);
return 0; }
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/unix/