先创建一个服务器
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include<string.h>
#define N 64
#define Server_port 5657
int main()
{
int fd = -1;
struct sockaddr_in sin;
// struct in_addr s_addr;
// sin.sin_addr = s_addr;
if((fd = socket(AF_INET,SOCK_STREAM,0))< 0 )
{
perror("socket");
exit(-1);
}
//端口复用函数
int on = 1;
int k = setsockopt(fd, SOL_SOCKET,SO_REUSEADDR, &on, sizeof(on));
if(k == -1)
{
perror("setsockopt");
return -1;
}
bzero(&sin,sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(Server_port);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
/* int flag = inet_pton(AF_INET, Server_IP,(void *)&sin.sin_addr.s_addr);
if(flag != 1)
{
perror("inet_pton");
exit(-1);
}
*/
if( bind(fd,(const struct sockaddr *)&sin,sizeof(sin)) < 0 )
{
perror("bind");
exit(-1);
}else{
printf("bind success!\n");
}
if( listen(fd,5) < 0 )
{
perror("listen");
exit(-1);
}else{
printf("listening!\n");
}
struct sockaddr_in client;
int n = sizeof(client);
int newfd = -1;
newfd = accept(fd,(struct sockaddr *)&client, &n);
if( newfd < 0 )
{
printf("no accept\n");
perror("accept");
exit(-1);
}else{
printf("accept success!\n");
}
printf("client ip:%s\nclient port:%d\n", inet_ntoa(client.sin_addr),
ntohs(client.sin_port));
char buff[N];
int ret = -1;
while(1)
{
bzero(buff,N);
ret = read(newfd,buff,N);
if(ret < 0)
{
perror("read");
return -1;
}else if(ret == 0)
{
close(newfd);
break;
}else if( strcmp(buff,"quit\n") == 0)
{
close(newfd);
break;
}
printf("client : %s\n",buff);
}
close(fd);
return 0;
}
创建一个客户端
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include<string.h>
#define N 64
#define Server_port 5002
#define Server_IP "127.0.0.1"
#define Client_port 9099
int main()
{
int fd = -1;
struct sockaddr_in sin;
if((fd = socket(AF_INET,SOCK_STREAM,0))< 0 )
{
perror("socket");
exit(-1);
}
bzero(&sin,sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(5657);
sin.sin_addr.s_addr = htonl(INADDR_ANY); //可通过任意IP连接服务器
// int flag = inet_pton(AF_INET, Server_IP,(void *)&sin.sin_addr.s_addr);
// if(flag != 1)
// {
// perror("inet_pton");
// exit(-1);
// }
if( connect(fd,(const struct sockaddr *)&sin,sizeof(sin)) < 0 )
{
perror("connect");
exit(-1);
}else{
printf("connect success!\n");
}
char buff[N];
while(1)
{
printf("Clinet input: ");
fgets(buff,N,stdin);
write(fd,buff,strlen(buff));
if( strcmp(buff,"quit\n") == 0) break;
}
close(fd);
return 0;
}