33{
34 if (m_fd > 0) {
36 }
37 sockaddr_in addr;
38 memset(&addr, 0, sizeof(sockaddr_in));
39 addr.sin_family = AF_INET;
40 addr.sin_addr.s_addr = INADDR_ANY;
41 addr.sin_port = htons(m_port);
42
43 m_fd = socket(PF_INET, SOCK_STREAM, 0);
44 if (m_fd == -1) {
45 m_fd = 0;
46 throw (
IOException(
"Fail to create a server socket."));
47 }
48 int enable = 1;
49 if (setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) {
50 m_fd = 0;
51 throw (
IOException(
"Fail to set resue address for the socket."));
52 }
53 struct hostent* host = NULL;
54 host = gethostbyname(m_ip.c_str());
55 if (host == NULL) {
56 unsigned long ip_address = inet_addr(m_ip.c_str());
57 if ((signed long) ip_address < 0) {
58 throw (std::exception());
59
60 } else {
61 host = gethostbyaddr((char*)&ip_address, sizeof(ip_address), AF_INET);
62 }
63 }
64 if (host == NULL) {
65 throw (
IOException(
"Fail to get host ip: %s", m_ip.c_str()));
66 }
67 addr.sin_addr.s_addr = (*(unsigned long*)host->h_addr_list[0]);
68
69 if (bind(m_fd, (const sockaddr*) & (addr), sizeof(sockaddr_in)) != 0) {
70 throw (
IOException(
"Fail to bind the socket. %s:%d", m_ip.c_str(), m_port));
71 }
72 if (listen(m_fd, nqueue) != 0) {
73 throw (
IOException(
"Fail to listen to the socket."));
74 }
75 return m_fd;
76}