ubuntu下udp源码
时间: 2023-08-17 16:02:17 浏览: 87
linux下的udp源代码
3星 · 编辑精心推荐
在Ubuntu下,我们可以使用C语言编写UDP的源代码。下面是一个简单的UDP客户端和服务器的示例:
UDP服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define BUF_SIZE 1024
int main()
{
int sockfd;
struct sockaddr_in server_addr, client_addr;
char buffer[BUF_SIZE];
// 创建socket
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket error");
exit(1);
}
// 设置服务器地址
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// 绑定socket到地址和端口
if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind error");
exit(1);
}
printf("UDP server listening on port %d...\n", PORT);
while (1) {
socklen_t addr_len = sizeof(struct sockaddr_in);
// 接收消息
int received_bytes = recvfrom(sockfd, buffer, BUF_SIZE, 0, (struct sockaddr*)&client_addr, &addr_len);
buffer[received_bytes] = '\0';
printf("Received message from client: %s\n", buffer);
// 发送响应
char response[] = "Hello from server!";
sendto(sockfd, response, strlen(response), 0, (struct sockaddr*)&client_addr, addr_len);
}
close(sockfd);
return 0;
}
```
UDP客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8888
#define BUF_SIZE 1024
int main()
{
int sockfd;
struct sockaddr_in server_addr;
char buffer[BUF_SIZE];
// 创建socket
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket error");
exit(1);
}
// 设置服务器地址
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
while (1) {
// 输入消息
printf("Enter message: ");
fgets(buffer, BUF_SIZE, stdin);
buffer[strlen(buffer) - 1] = '\0';
// 发送消息
sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr*)&server_addr, sizeof(server_addr));
// 接收响应
socklen_t addr_len = sizeof(struct sockaddr_in);
int received_bytes = recvfrom(sockfd, buffer, BUF_SIZE, 0, (struct sockaddr*)&server_addr, &addr_len);
buffer[received_bytes] = '\0';
printf("Received response from server: %s\n", buffer);
}
close(sockfd);
return 0;
}
```
可以在Ubuntu上使用gcc编译器编译上述代码:
```
gcc server.c -o server
gcc client.c -o client
```
然后分别运行服务器和客户端:
```
./server
./client
```
服务器将监听8888端口并等待客户端发送消息,客户端将接收用户输入的消息并发送至服务器,服务器接收到消息后发送响应到客户端,并将响应打印出来。
阅读全文