當前位置:編程學習大全網 - 源碼下載 - 能否給我壹個用純C編寫的UDP發送和接收的程序

能否給我壹個用純C編寫的UDP發送和接收的程序

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;

}

  • 上一篇:求大智慧條件選股公式:macd白線上穿黃線後,股價回落至白線與黃線第壹次相交或粘合的股票
  • 下一篇:我的麻友們
  • copyright 2024編程學習大全網