#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main( int
argc, char **argv)
{
int
listenfd,connfd,n, ret;
struct
sockaddr_in servaddr, cliaddr;
socklen_t clilen;
pid_t childpid;
char
mesg[1000], *peeraddr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if
(listenfd < 0) {
printf ( "create socket error\n" );
return
-1;
}
printf ( "create socket success\n" );
memset (&servaddr, 0, sizeof (servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(6789);
ret = bind(listenfd, ( struct
sockaddr *)&servaddr, sizeof (servaddr));
if
(ret == -1) {
printf ( "bind error\n" );
return
-1;
}
printf ( "bind success\n" );
ret = listen(listenfd, 1024);
if
(ret == -1) {
printf ( "listen error\n" );
return
-1;
}
printf ( "listening...\n" );
for
(;;) {
clilen = sizeof (cliaddr);
connfd = accept(listenfd, ( struct
sockaddr *)&cliaddr, &clilen);
printf ( "Accept request from %s\n" , inet_ntoa(cliaddr.sin_addr));
n = read(connfd, mesg, 1000);
if
(n < 0) {
printf ( "read error!\n" );
}
printf ( "Received:%s\n" , mesg);
close(connfd);
}
}
|