本帖最后由 xiaoye 于 2015-9-30 18:45 编辑
最近在看linux编程,这是在网上找的一个代码,直接复制下来代码会有问题,这个已经修改过了
服务器端
[C] 纯文本查看 复制代码 #include"stdio.h"
#include "stdlib.h"
#include "string.h"
#include"errno.h"
#include"sys/types.h"
#include"sys/socket.h"
#include"netinet/in.h"
#define DEFAULT_PORT 6666
#define MAXLINE 4096
int main(int argc ,char ** argv){
int socket_fd,connect_fd;
struct sockaddr_in serveraddr;
char buff[MAXLINE];
int n ;
if ((socket_fd=socket(AF_INET,SOCK_STREAM,0))==-1){
printf("create socket error:%s(errorno:%d)",strerror(errno),errno);
exit(0);
}
memset(&serveraddr,0,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);
serveraddr.sin_port=htons(DEFAULT_PORT);
if(bind(socket_fd,(struct sockaddr *)&serveraddr,sizeof(serveraddr))==-1){
printf("bind socket error:%s(errorno:%d)",strerror(errno),errno);
exit(0);
}
if(listen(socket_fd,10)==-1){
printf("listen socket error");
exit(0);
}
printf("====================wait for client==============");
while(1){
if((connect_fd=accept(socket_fd,(struct sockaddr*)NULL,NULL))==-1){
printf("accept error:%s(errorno:%d)\n",strerror(errno),errno);
sleep(10);
continue;
}
n=recv(connect_fd,buff,MAXLINE,0);
if(!fork()){
if(send(connect_fd,"hello,you are connect!\n",26,0)==-1){
perror("send error");
close(connect_fd);
exit(0);
}
buff[n]='\n';
printf("recv msg from client:%s",buff);
close(connect_fd);
exit(0);
}
close(socket_fd);
}
}
客户端
[C] 纯文本查看 复制代码 #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define MAXLINE 4096
int main(int argc, char ** argv){
int sockfd,n ,rec_len;
char recvline[4096],sendline[4096];
char buf[MAXLINE];
struct sockaddr_in serveraddr;
if(argc!=2){
printf("usage:./client <ipaddress> \n");
exit(0);
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0){
printf("create socket error ");
exit(0);
}
memset(&serveraddr, 0,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(6666);
if(inet_pton(AF_INET,argv[1],&serveraddr.sin_addr)<=0){
printf("inet_ptos error");
exit(0);
}
if(connect(sockfd,(struct sockaddr * )&serveraddr,sizeof(serveraddr))<0){
printf("connetc error");
exit(0);
}
printf("send msg to server :\n");
fgets(sendline,4096,stdin);
if(send(sockfd,sendline,strlen(sendline),0)<=0){
printf("send msg error");
exit(0);
}
if((rec_len=recv(sockfd,buf,MAXLINE,0))<=0){
printf("recv error ");
exit(0);
}
buf[rec_len]='\n';
printf("recv:%s",buf);
exit(0);
}
|