본문 바로가기

UNIX_LINUX_C_C++

jinie_lib_winwock2

jinie_lib_winsock2.h
번호: 56 / 작성자: jinyedge / 등록일: 2002-05-07 20:32:34 / 조회: 133
#ifndef _JINIE_LIB_WINSOCK2_H
#define _JINIE_LIB_WINSOCK2_H

/*NET_BEGIN*/
int get_server_sock(int port);//서버소켓을 리턴한다.
int get_client_sock(char *server_ip, int port);//소켓을 리턴한다.
int sock_send(int s, char buf[]);
int sock_recv(int s, char buf[], int buf_len);

#endif

jinie_lib_winsosk2.c

번호: 57 / 작성자: jinyedge / 등록일: 2002-05-07 20:32:52 / 조회: 180
#include "jinie_lib_winwock2.h"

/*NET_BEGIN*/

//------------------------
int get_server_sock(int port){//서버소켓을 리턴한다.
int SERVER, on;
struct sockaddr_in my_addr;
int r_code;

my_addr.sin_family = AF_INET;
my_addr.sin_port = htons((u_short)port);
my_addr.sin_addr.s_addr = INADDR_ANY;

r_code = SERVER = socket(AF_INET, SOCK_STREAM, 0);
if(r_code < 0){return -1;}
r_code = setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
if(r_code < 0){return -1;}

r_code = bind(SERVER, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
if(r_code < 0){return -1;}

return SERVER;
}

//------------------------
int get_client_sock(char *server_ip, int port){//소켓을 리턴한다.
int NET_CONN;
struct sockaddr_in server_addr;
int r_code;

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons((u_short)port);
server_addr.sin_addr.s_addr = inet_addr(server_ip);

r_code = NET_CONN = socket(AF_INET, SOCK_STREAM, 0);
if(r_code < 0){return -1;}

r_code = connect(NET_CONN, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
if(r_code < 0){return -1;}

return NET_CONN;
}

//------------------------
int sock_send(int s, char buf[]){
return send(s, buf, strlen(buf), 0);
}

//------------------------
int sock_recv(int s, char buf[], int buf_len){
int len;
len = recv(s, buf, buf_len, 0);

if(len < 0){return len;}

buf[len] = '\0';
return len;
}