客户端
#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
int main(int argc,char **argv)
{
int sockfd;
int n;
struct sockaddr_in servaddr,cliaddr;
char sendline[1000];
char recvline[1000];
if(argc != 2)
{
printf("usage:client <IP address>\n");
exit(-1);
}
sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd == -1)
{
printf("socket wrong\n");
exit(-1);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
servaddr.sin_port = htons(32000);
// connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
while(fgets(sendline,100,stdin) != NULL)
{
sendto(sockfd,sendline,strlen(sendline),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
n = recvfrom(sockfd,recvline,1000,0,NULL,NULL);
recvline[n] = '\0';
fputs(recvline,stdout);
}
return 0;
}
服务器
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
int main()
{
int fd;
int n;
pid_t pid;
int i;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
char msg[1000];
fd = socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(32000);
bind(fd,(struct sockaddr *)&servaddr,sizeof(servaddr));
// listen(listenfd,1024);
for(;;)
{
clilen = sizeof(cliaddr);
// connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
// if((pid = fork()) == 0)
{
// close(listenfd);
while(1)
{
n = recvfrom(fd,msg,1000,0,(struct sockaddr*)&cliaddr,&clilen);
if(n == 0)
{
printf("client is close!\n");
break;
}
printf("************************\n");
msg[n] = '\0';
printf("%s\n",msg);
printf("************************\n");
for(i = 0;i < n;i++)
{
if((msg[i] >= 'a') && (msg[i] <= 'z'))
{
msg[i] = msg[i] - 32;
}
}
sendto(fd,msg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
}
// break;
// close(connfd);
}
}
// close(listenfd);
return 0;
}