?? udp_client2.c
字號:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <arpa/inet.h>#include <string.h>#include <errno.h>#define BUFFER_SIZE 1024int main(int argc, char **argv){ int fd; // XXX: step 1, socket(); int socket(int domain, int type, int protocol); if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { fprintf(stderr, "Create a new UDP socket failed: %s\n", strerror(errno)); exit(1); } char line[BUFFER_SIZE]; struct sockaddr_in remote_address; ssize_t sent; memset(&remote_address, 0, sizeof(remote_address)); remote_address.sin_family = PF_INET; remote_address.sin_port = htons(atoi(argv[2])); remote_address.sin_addr.s_addr = inet_addr(argv[1]); // XXX: step 2, bind(); optional // XXX: step 3, connect(), optional // int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen); if (connect(fd, (struct sockaddr *) &remote_address, sizeof(remote_address)) < 0) { fprintf(stderr, "connect() failed: %s\n", strerror(errno)); exit(1); } // char *fgets(char *s, int size, FILE *stream); while (fgets(line, BUFFER_SIZE, stdin)) { // XXX: step 4, sendto()/recvfrom resend: // ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); //if ((sent = sendto(fd, line, strlen(line), 0, (struct sockaddr *) &remote_address, sizeof(remote_address))) < 0) //ssize_t send(int s, const void *buf, size_t len, int flags); //if ((sent = send(fd, line, strlen(line), 0)) < 0) if ((sent = sendto(fd, line, strlen(line), 0, NULL, 0)) < 0) { if (errno == EINTR) { goto resend; } else { fprintf(stderr, "sendto() failed: %s\n", strerror(errno)); } } else { fprintf(stdout, "Sent %d bytes to remote host.\n", sent); } struct sockaddr_in peer_address; socklen_t peer_address_length; ssize_t n; peer_address_length = sizeof(peer_address); re_receive: //ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen); if ((n = recvfrom(fd, line, BUFFER_SIZE, 0, (struct sockaddr *) &peer_address, &peer_address_length)) < 0) { if (errno == EINTR) { goto re_receive; } else { fprintf(stderr, "recvfrom() failed: %s\n", strerror(errno)); } } else { fprintf(stdout, "INFO: read %d bytes from %s:%d\n", n, inet_ntoa(peer_address.sin_addr), ntohs(peer_address.sin_port));#if 0 int i; for (i = 0; i < n; i++) { fprintf(stdout, "0x%x", buffer[i]); }#endif line[n] = '\0'; fprintf(stdout, "DEBUG: %s\n", line); } } // XXX: step 5, close() return 0;}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -