엔지니어가 되고 싶은 공돌이
12. UDP 본문

12. 1. Server UDP Socket
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<inttypes.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#define PORTNUM 1234
int main(void){
char buf[256];
struct sockaddr_in sin, cli;
int sd, ns, clientlen = sizeof(cli);
if((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket");
exit(1);
}
memset((char *)&sin, '\0', sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(PORTNUM);
sin.sin_addr.s_addr = inet_addr("0.0.0.0"); // 0.0.0.0은 모든 IP로부터의 요청을 받는다는 뜻.
if(bind(sd, (struct sockaddr *)&sin, sizeof(sin))){
perror("bind");
exit(1);
}
while (1) {
if ((recvfrom(sd, buf, 255, 0,
(struct sockaddr *)&cli, &clientlen)) ==-1) {
perror("recvfrom");
exit(1);
}
printf("** From Client : %s\n", buf);
strcpy(buf, "Hello Client");
if ((sendto(sd, buf, strlen(buf)+1, 0,
(struct sockaddr *)&cli, sizeof(cli))) == -1) {
perror("sendto");
exit(1);
}
}
return 0;
}
12. 2. Client UDP Socket
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<inttypes.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#define PORTNUM 1234
int main(void){
int sd;
char buf[256];
struct sockaddr_in sin;
if((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket");
exit(1);
}
memset((char *)&sin, '\0', sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port = htons(PORTNUM);
sin.sin_addr.s_addr = inet_addr("0.0.0.0"); // 정확한 포트명 입력하기
strcpy(buf,"I am a client.");
if (sendto(sd,buf,strlen(buf)+1,0,
(structsockaddr*)&sin,sizeof(sin)) ==-1){
perror("sendto");
exit(1);
}
n = recvfrom(sd, buf, 255, 0, NULL, NULL);
buf[n] = '\0';
printf("** From Server : %s\n", buf);
return 0;
}
'Computer Science > Unix' 카테고리의 다른 글
11. TCP (0) | 2025.03.18 |
---|---|
10. Socket (0) | 2025.03.17 |
09. Thread (0) | 2025.03.16 |
08. Fork and Exec (0) | 2025.03.15 |
07. Process (0) | 2025.03.14 |
Comments