能否给我一个用纯C编写的UDP发送和接收的程序

能否给我一个用纯C编写的UDP发送和接收的程序,第1张

UDP的,你看下

1.服务器端实现

程序在收到客户端发送来的消息后,给客户端发送消息,提示客户端收到了该消息

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>

#include <stdio.h>

#include <unistd.h>

int main(int argc, char *argv[])

{

int sock, length, fromlen, n

struct sockaddr_in server

struct sockaddr_in from

char buf[1024]

//要求执行是输入端口信息

if (argc!= 2) {

printf( "Usage: %s port_num\n",argv[0])

return 1

}

//创建通信所需的套接字,并与地址和端口信息帮定

sock=socket(AF_INET, SOCK_DGRAM, 0)

if (sock <0){

perror("cannot create communicating socket")

return 1

}

length = sizeof(server)

bzero(&server,length)

server.sin_family=AF_INET

server.sin_addr.s_addr=INADDR_ANY

server.sin_port=htons(atoi(argv[1]))

if (bind(sock,(struct sockaddr *)&server,length)<0){

perror("cannot bind the socket")

close(sock)

return 1

}

fromlen = sizeof(struct sockaddr_in)

//读取客户端发送来的信息,显示后,发回相关信息给客户端

while (1) {

n = recvfrom(sock,buf,sizeof(buf),0,(struct sockaddr *)&from,&fromlen)

if (n <0) {

perror("cannot receive date from client")

break

}

write(STDOUT_FILENO,"server: Received a datagram: ",29)

write(STDOUT_FILENO,buf,n)

n = sendto(sock,"send message to client\n",22,

0,(struct sockaddr *)&from,fromlen)

if (n <0) {

perror("cannot send data to the client")

break

}

}

close(sock)

return 0

}

2.客户端实现

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <netdb.h>

#include <stdio.h>

#include <unistd.h>

int main(int argc, char *argv[])

{

int sock, length, n

struct sockaddr_in server, from

struct hostent *hp

char buffer[256]

//判断输入参数是否符合要求

if (argc != 3) {

printf("Usage: %s server_ip port_num\n",argv[0])

return 1

}

//创建通信套接字

sock= socket(AF_INET, SOCK_DGRAM, 0)

if (sock <0) {

perror("cannot create communicating socket")

return 1

}

server.sin_family = AF_INET

hp = gethostbyname(argv[1])

if (hp==0) {

perror("cannot get the server ip address")

return 1

}

bcopy((char *)hp->h_addr,

(char *)&server.sin_addr,

hp->h_length)

server.sin_port = htons(atoi(argv[2]))

length=sizeof(struct sockaddr_in)

printf("(client) enter the message: ")

bzero(buffer,256)

fgets(buffer,255,stdin)

//发送数据给指定服务器

n=sendto(sock,buffer,strlen(buffer),0,&server,length)

if (n <0){

perror("cannot get message from the client")

return 1

}

//从服务器中接受数据

bzero(buffer,256)

n = recvfrom(sock,buffer,256,0,&from, &length)

if (n <0) {

perror("cannot send message to the server")

return 1

}

printf("client got message : %s\n",buffer)

close(sock)

return 0

}

1。TCP是基于连接的,UDP是基于无连接 2。对系统资源的要求(TCP较多,UDP少) 3。UDP程序结构较简单 4。流模式与数据报模式 5。TCP保证数据正确性,UDP可能丢包,TCP保证数据顺序,UDP不保证


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12000838.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存