gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
make a C program to send a udp packet
- User
make a C program to send a udp packet
- Assistant
Sure! Here is a sample C program that sends a UDP packet using sockets:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> #define SERVER_IP "127.0.0.1" // Change this to the IP address of the destination server #define SERVER_PORT 12345 // Change this to the desired destination port int main() { int sockfd; struct sockaddr_in serverAddr; // Create UDP socket sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("Error creating socket"); return -1; } // Set up server address memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(SERVER_PORT); if (inet_pton(AF_INET, SERVER_IP, &(serverAddr.sin_addr)) <= 0) { perror("Error setting server address"); close(sockfd); return -1; } // Send packet const char *message = "Hello, UDP Server!"; int len = strlen(message); if (sendto(sockfd, message, len, 0, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != len) { perror("Error sending packet"); close(sockfd); return -1; } printf("UDP packet sent successfully.\n"); // Close socket close(sockfd); return 0; }