服务器端
#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
main()
{
int nSocket,nCliSocket;
int nCliLen;
struct sockaddr_in sin,cli_sin;
//struct sockaddr_in *p = &sin;
char buf[INET_ADDRSTRLEN+1];
char recvBuf[20];
memset(buf,0x00,sizeof(buf));
memset(recvBuf,0x00,sizeof(recvBuf));
if((nSocket=socket(PF_INET,SOCK_STREAM,0))<0)
{
fprintf(stderr,"socket errno:%s\n",strerror(errno));
exit(0);
}
bzero(&sin,sizeof(struct sockaddr_in));
//memset(p,0x00,sizeof(struct sockaddr_in));
sin.sin_family=AF_INET;
sin.sin_addr.s_addr=htonl(INADDR_ANY);
sin.sin_port=htons(6666);
if(bind(nSocket,(struct sockaddr *)&sin,sizeof(sin))<0)
{
fprintf(stderr,"bind errno:%s \n",strerror(errno));
close(nSocket);
exit(0);
}
printf("Bind success! \n");
listen(nSocket,SOMAXCONN);
//sleep(600);
while(1)
{
nCliLen = sizeof(cli_sin);
if((nCliSocket = accept(nSocket,(struct sockaddr *)&cli_sin,&nCliLen))<0)
{
fprintf(stderr,"accept errno:%s \n",strerror(errno));
continue;
}
printf("accept connection from \ %s:%d \n",inet_ntop(AF_INET,&cli_sin.sin_addr,buf,sizeof(buf)),ntohs(cli_sin.sin_port));
recv(nCliSocket,recvBuf,sizeof(recvBuf),0);
printf("receive data : %s \n",recvBuf);
close(nCliSocket);
continue;
}
close(nSocket);
return;
}
客户端
#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
main()
{
int nSocket;
struct sockaddr_in sin;
//struct sockaddr_in *p = &sin;
char sendBuf[20];
memset(sendBuf,0x00,sizeof(sendBuf));
strcpy(sendBuf,"send ok");
if((nSocket=socket(PF_INET,SOCK_STREAM,0))<0)
{
fprintf(stderr,"socket errno:%s\n",strerror(errno));
exit(0);
}
bzero(&sin,sizeof(struct sockaddr_in));
//memset(p,0x00,sizeof(struct sockaddr_in));
if(inet_pton(AF_INET,"192.168.123.12",&(sin.sin_addr))!=1)
{
fprintf(stderr,"inet_pton error:%s\n",strerror(errno));
exit(0);
}
sin.sin_family=AF_INET;
//sin.sin_addr.s_addr=htonl("127.0.0.1");
sin.sin_port=htons(6666);
if(connect(nSocket,(struct sockaddr *)&sin,sizeof(sin))<0)
{
fprintf(stderr,"connect errno:%s \n",strerror(errno));
close(nSocket);
exit(0);
}
printf("connect success! \n");
send(nSocket,sendBuf,sizeof(sendBuf),0);
//listen(nSocket,SOMAXCONN);
//sleep(60);
close(nSocket);
return;
}