• 客户端代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include<netinet/in.h>
#include <errno.h> int main(int argc, char** argv)
{
int socketfd = ;
struct sockaddr_in server_addr;
char recvbuf[];
int port = ;
int nbyte; if((socketfd = socket(AF_INET, SOCK_DGRAM, )) == ){
fprintf(stderr, "socket Error:%s\n\a", strerror(errno));
exit();
} bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); int len = sizeof(struct sockaddr_in); while(){
if(sendto(socketfd, "Hello Fredric", strlen("Hello Fredric"), ,
(struct sockaddr *)&server_addr, len) == -){ fprintf(stderr, "sendto Error:%s\n\a", strerror(errno));
close(socketfd);
exit();
} if((nbyte = recvfrom(socketfd, recvbuf, , , (struct sockaddr *)&server_addr, &len)) == -){
fprintf(stderr, "recvfrom Error:%s\n\a", strerror(errno));
close(socketfd);
exit();
} recvbuf[nbyte] = '\0';
printf("recv data is:%s\n",recvbuf);
} close(socketfd); exit();
}
  • 服务器端代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include<netinet/in.h>
#include <errno.h> int main(int argc, char** argv){ int socketfd = ;
struct sockaddr_in server_addr;
char recvbuf[];
char sendbuf[];
int port = ;
int nbyte; if((socketfd = socket(AF_INET, SOCK_DGRAM, )) == ){
fprintf(stderr, "socket Error:%s\n\a", strerror(errno));
exit();
} bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); if((bind(socketfd, &server_addr, sizeof(server_addr))) == -){
fprintf(stderr, "bind Error:%s\n\a", strerror(errno));
exit();
}
int len = sizeof(struct sockaddr_in);
while(){
if((nbyte = recvfrom(socketfd, recvbuf, , , (struct sockaddr*)&server_addr, &len)) == -){
fprintf(stderr, "recvfrom Error:%s\n\a", strerror(errno));
close(socketfd);
exit();
} recvbuf[nbyte] = '\0';
printf("recv data is:%s\n",recvbuf); printf("Input:");
scanf("%s", sendbuf); if((nbyte = sendto(socketfd, sendbuf, sizeof(sendbuf),
, (struct sockaddr*)&server_addr, len)) == -){
fprintf(stderr, "sendto Error:%s\n\a", strerror(errno));
close(socketfd);
exit();
}
} close(socketfd);
exit();
}
05-11 13:32