server.c & client.c socket编程学习

server.c

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main(int argc,char *argv[])
{
int sockfd_server,sockfd_client;
struct sockaddr_in serveraddr,clientaddr,client_addr;
int addrlen,port;
char buffer[100];
FILE *fp;

fp=fopen("/var/portnumber","w");
fprintf(fp,"%d",100);
fclose(fp);
if (argc!=2)
{
puts("need two paramter");
exit(1);
}
port=atoi(argv[1]);
//printf("port is %d\n",port);
if((sockfd_server=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket creat error\n");
exit(1);
}
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(port);
serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(sockfd_server,(struct sockaddr *)&serveraddr,sizeof(serveraddr))==-1)
{
perror("socket bind error\n");
exit(1);
}
listen(sockfd_server,5);
//struct sockaddr_in serverinfo;
//int serverinfo_len=sizeof(serverinfo);
//getsockname(sockfd_server, (struct sockaddr *)&serverinfo, &serverinfo_len);
//printf("my port is %d\n",ntohs(serverinfo.sin_port));
addrlen=sizeof(clientaddr);
while(1)
{
if((sockfd_client=accept(sockfd_server,(struct sockaddr *)&clientaddr,&addrlen))==-1)
{
perror("accpet error\n");
exit(1);
}
printf("server got connection from: %s \n",inet_ntoa(clientaddr.sin_addr));

if(recv(sockfd_client,buffer,100,0)==-1)
{
perror("recv error");
exit(1);
}
printf("recived:%s\n",buffer);

char *buffer2="hello i'm the server";
if(send(sockfd_client,buffer2,20,0)==-1)
{
exit(1);
}
close(sockfd_client);
}
close(sockfd_server);
return 0;
}



client.c

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main(int argc,char *argv[])
{
int sockfd;
char buff[]="this is from the client";
struct sockaddr_in serveraddr;
if(argc!=2)
{
printf("need two parameters \n");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket creat error\n");
exit(1);
}
int port=atoi(argv[1]);
//printf("input a port to connect to:");
//scanf("%d",&port);
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(port);
serveraddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(connect(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr))==-1)
{
perror("connect error\n");
exit(1);
}
puts("connect success");
int bufferlen=strlen(buff);
if(send(sockfd,buff,bufferlen,0)==-1)
{
perror("send error");
exit(1);
}
if(recv(sockfd,buff,100,0)==-1)
{
perror("recv error");
exit(1);
}
printf("send from server:%s\n",buff);
close(sockfd);
return 0;
}


Makefile:

all:server client
server:server.c
gcc -o server server.c
client:client.c
gcc -o client client.c
clean:
rm -f client server

没有评论: