본문 바로가기

UNIX_LINUX_C_C++

bind error 방지 하기

int make_sock(int port, int users)
{
int sock;
struct sockaddr_in my_addr;

int iSockOpt;

if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("SOCKET");
return (-1);
}

my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8); // set the rest of the struct

// prevent bind error
iSockOpt = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &iSockOpt, sizeof(iSockOpt));

if(bind(sock, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) < 0)
{
perror("SOCKET BIND");
close(sock);
return (-1);
}

if(listen(sock, users) < 0)
{
perror("SOCKET LISTEN");
close(sock);
return (-1);
}

return sock;
}