网络编程
客户端代码如下
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<arpa/inet.h>
#include<sys/socket.h>
int main(){
int ssock,len;
char buf[100];
char client[100]="this is from client";//用来发送给server
struct sockaddr_in server_addr;//结构体sockaddr_in包含里各种参数
if((ssock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0){
perror("socket error");//如果socket错误,会弹出该条信息
exit(1);
}
len=sizeof(server_addr);
memset(&server_addr,0,len);//相当于用len个0填充server_addr
server_addr.sin_family=AF_INET;//协议族
server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");//地址
server_addr.sin_port=htons(7758);//端口
memset(buf,0,100);
if(connect(ssock,(struct sockaddr *)&server_addr,len)<0){
perror("connect error");
exit(1);
}//连接
int n;
if((n=read(ssock,buf,100))<=0){
perror("read error");
exit(1);
}//从ssock中读取100个字节到buf中
if(write(ssock,client,100)<=0){
perror("write error");
exit(1);
}//把client中的100个字节写入ssock
buf[n]='\0';//字符串末尾加个结束符号
close(ssock);//关闭
printf("read :%s\n",buf);//打印接收到的字符串
return 0;}
服务器端代码如下
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<sys/stat.h>
int main(){
int clen;
int ssock,csock;
struct sockaddr_in client_addr,server_addr;
char buf[100]="this is from server";
char cli[100];
if((ssock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0){
perror("socket error");
exit(1);
}
clen=sizeof(client_addr);
memset(&server_addr,0,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
server_addr.sin_port=htons(7758);
if(bind(ssock,(struct sockaddr *)&server_addr,sizeof(server_addr))<0){
perror("bind error");
exit(1);
}
if(listen(ssock,8)<0){
perror("listen error");
exit(1);
}
while(1){
csock=accept(ssock,(struct sockaddr *)&client_addr,&clen);
if(write(csock,buf,100)<=0)
perror("write error");
if(read(csock,cli,100)<=0){
perror("read error");
}
else
printf("from client %s\n",cli);
close(csock);
}
return 0;
}