반응형
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
/****************************************************************/
int socket_non_bolcking_mode_bind_listen(int port)
{
int fd;
struct sockaddr_in myAddr;
int flag;
int sockOpt=1;
int reUseOpt=1;
struct linger lin;
/* socket */
if (( fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
fprintf(stderr, "socket fail errno=%d(%s)\n", errno, strerror(errno));
return (-1);
}
/* socket option */
/* 소켓옵션의 경우 여러가지가 존재하므로 선택에 의해서 여러가지를 세팅하여 설정가능 */
lin.l_onoff = 1;
lin.l_linger = 0;
if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&lin, sizeof(lin)) < 0) {
fprintf(stderr,"setsockopt(SO_LINGER) fail; errno=%d(%s)\n",errno,strerror(errno));
return -1;
}
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&sockOpt, sizeof(sockOpt)) < 0) {
fprintf(stderr,"setsockopt(SO_KEEPALIVE) fail; errno=%d(%s)\n",errno,strerror(errno));
return -1;
}
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&reUseOpt, sizeof(reUseOpt)) < 0) {
fprintf(stderr,"setsockopt(SO_REUSEADDR) fail; errno=%d(%s)\n",errno,strerror(errno));
return -1;
}
/* set Non-Blocking Mode */
if ((flag = fcntl(fd, F_GETFL, 0)) < 0) {
fprintf(stderr,"fcntl(F_GETFL) fail; errno=%d(%s)\n",errno,strerror(errno));
close(fd);
return -1;
}
flag |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, flag) < 0) {
fprintf(stderr,"fcntl(F_SETFL) fail; errno=%d(%s)\n",errno,strerror(errno));
close(fd);
return -1;
}
/* server port and ip setting */
memset ((void*)&myAddr, 0x00, sizeof(myAddr));
myAddr.sin_family = AF_INET;
myAddr.sin_port = htons(port);
myAddr.sin_addr.s_addr = htonl(INADDR_ANY);
/* bind */
if (bind(fd, (struct sockaddr*)&myAddr, sizeof(myAddr)) < 0 ) {
fprintf(stderr,"bind fail errno=%d[%s]\n", errno, strerror(errno));
close(fd);
return -1;
}
/* listen */
if (listen(fd, SOMAXCONN) < 0) {
fprintf(stderr,"listen fail; errno=%d[%s]\n",errno,strerror(errno));
close(fd);
return -1;
}
return fd;
}
반응형