主机端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define portnumber 3333
int main(int argc,char *argv[])
{
int sockfd,new_fd;
struct sockaddr_in sever_addr;
struct sockaddr_in client_addr;
int sin_size,nbytes;
char buffer[1024];
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
fprintf(stderr,"socket error %s\n",strerror(errno));
exit(1);
}
bzero(&sever_addr,sizeof(struct sockaddr_in));
sever_addr.sin_family=AF_INET;
sever_addr.sin_addr.s_addr=htonl(INADDR_ANY);
sever_addr.sin_port=htons(portnumber);
if(bind(sockfd,(struct sockaddr*)(&sever_addr),sizeof(struct sockaddr))==-1)
{
fprintf(stderr,"bind error %s\n",strerror(errno));
exit(1);
}
if(listen(sockfd,5)==-1)
{
fprintf(stderr,"listen error %s\n",strerror(errno));
exit(1);
}
while(1)
{
sin_size=sizeof(struct sockaddr_in);
if((new_fd=accept(sockfd,(struct sockaddr*)(&client_addr),&sin_size))==-1)
{
fprintf(stderr,"accept error %s\n",strerror(errno));
exit(1);
}
fprintf(stderr,"sever get connection from %s\n",inet_ntoa(client_addr.sin_addr));
if((nbytes=read(new_fd,buffer,1024))==-1)
{
fprintf(stderr,"read error %s\n",strerror(errno));
exit(1);
}
buffer[nbytes]='\0';
printf("sever received %s\n",buffer);
close(new_fd);
}
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define portnumber 3333
int main(int argc,char *argv[])
{
int sockfd;
char buffer[1024];
struct sockaddr_in sever_addr;
struct hostent *host;
if(argc!=2)
{
fprintf(stderr,"usage:%s hostname \n",argv[0]);
exit(1);
}
if((host=gethostbyname(argv[1]))==NULL)
{
fprintf(stderr,"get host name eror\n");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
fprintf(stderr,"socket error:%s\n",strerror(errno));
exit(1);
}
bzero(&sever_addr,sizeof(sever_addr));
sever_addr.sin_family=AF_INET;
sever_addr.sin_port=htons(portnumber);
sever_addr.sin_addr=*((struct in_addr*)host->h_addr);
if(connect(sockfd,(struct sockaddr*)(&sever_addr),sizeof(struct sockaddr))==-1)
{
fprintf(stderr,"connect error:%s\n",strerror(errno));
exit(1);
}printf("please input char:\n");
fgets(buffer,1024,stdin);
write(sockfd,buffer,strlen(buffer));
close(sockfd);
exit(0);
}