====================server.c===================
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define MAXLINE 50
typedef struct sockaddr SA;
int main(int argc, char **argv)
{
int listenfd,connfd;
socklen_t clilen;
struct sockaddr_in myaddr,cliaddr;
char buf[MAXLINE]="welcome to TCP server";
if((listenfd = socket(PF_INET,SOCK_STREAM,0))<0) //创建套接字
{
perror("fail to socket");
exit(-1);
}
bzero(&myaddr,sizeof(myaddr));
myaddr.sin_family =PF_INET;
myaddr.sin_addr.s_addr =inet_addr("192.168.0.21");
myaddr.sin_port =htons(8888);
if(bind(listenfd,(SA*)&myaddr,sizeof(myaddr))<0) //绑定
{
perror("fail to bind");
exit(-1);
}
listen(listenfd,5);//监听
while(1)
{
clilen = sizeof(cliaddr);
connfd = accept(listenfd,(SA*)&cliaddr,&clilen);//等待接收链接
printf("connection from %s,port %d/n",
inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
if(send(connfd,buf,sizeof(buf),0)<0)//发送
{
printf("send failed");
break;
}
close(connfd);
}
return 0;
}
==================client.c===================
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define MAXLINE 50
typedef struct sockaddr SA;
int main(int argc, char **argv)
{
int sockfd,nbyte;
struct sockaddr_in servaddr,myaddr;
char buf[MAXLINE];
if((sockfd = socket(PF_INET,SOCK_STREAM,0))<0) //创建套接字
{
perror("fail to socket");
exit(-1);
}
bzero(&servaddr,sizeof(servaddr));//清零
servaddr.sin_family =PF_INET;
servaddr.sin_addr.s_addr =inet_addr("192.168.0.21");
servaddr.sin_port =htons(8888);
if(connect(sockfd,(SA*)&servaddr,sizeof(servaddr))<0) //链接
{
perror("fail to connect");
exit(-1);
}
if((nbyte = recv(sockfd,buf,MAXLINE,0))<0)//接收
{
perror("fail to recv");
exit(-1);
}
printf("recv from server:%s",buf);
return 0;
}