Skip to content

Instantly share code, notes, and snippets.

@surinoel
Last active July 23, 2019 02:55
Show Gist options
  • Save surinoel/a60d68ebc5187a634cdf3763a251b5de to your computer and use it in GitHub Desktop.
Save surinoel/a60d68ebc5187a634cdf3763a251b5de to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define TCP_PORT 5100
#define BUF_SIZE 256
int main(int argc, char **argv)
{
int ssock;
int clen;
struct sockaddr_in servaddr;
char buf[BUF_SIZE];
if(argc < 2) {
printf("Usage :%s IP_ADDRESS\n", argv[0]);
return -1;
}
if((ssock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
// 문자열을 IP 주소 포맷으로 바꿔주는 과정
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
// htons의 매개변수는 uint32_t 혹은 uint16_t로, 만일 argv로 받을 때 atoi 처리를 해야만 한다
servaddr.sin_port = htons(TCP_PORT);
clen = sizeof(servaddr);
if(connect(ssock, (struct sockaddr *)&servaddr, clen) < 0) {
perror("connect()");
return -1;
}
fgets(buf, BUF_SIZE, stdin);
if(write(ssock, buf, BUF_SIZE) <= 0) {
perror("write");
return -1;
}
memset(buf, 0, BUF_SIZE);
if(read(ssock, buf, BUF_SIZE) <= 0) {
perror("read");
return -1;
}
printf("Received data : %s", buf);
close(ssock);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define TCP_PORT 5100
#define BUF_SIZE 256
int main(int argc, char **argv)
{
int ssock;
socklen_t clen;
int n;
struct sockaddr_in servaddr, cliaddr;
char buf[BUF_SIZE] = "Hello World";
if((ssock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
perror("socket()");
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(TCP_PORT);
if(bind(ssock, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("bind");
return -1;
}
/* 동시에 접속하는 클라이언트의 처리를 위한 대기 큐를 설정 */
if(listen(ssock, 8) < 0) {
perror("listen");
return -1;
}
clen = sizeof(cliaddr);
while(1) {
/* blocking 상태로 소켓이 연결될 때까지 대기한 후 생성 */
int csock = accept(ssock, (struct sockaddr *)&cliaddr, &clen);
printf("Client is connected : %s\n", inet_ntoa(cliaddr.sin_addr));
if((n = read(csock, buf, BUF_SIZE)) <= 0) {
perror("read");
}
printf("Received data : %s\n", buf);
// 서버에서 write/read를 할 때의 fd는 클라이언트 fd
if(write(csock, buf, n) <= 0) {
perror("write");
}
close(csock);
}
close(ssock);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment