//FUNCTION: ***listensocket***
bool Socket::listensocket(std::string localaddress)
{
if ((fd = socket(domain, type, 0)) < 0)
{
syslog(LOG_ERR, "Listen socket, socket() failed");
return false;
}
struct mysockaddr localname = stringtosockaddr(localaddress);
if (domain == AF_INET)
{
int i = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
}
else
unlink(localaddress.c_str());
if (bind(fd, (struct sockaddr *) &localname, SOCK_SIZE(domain)) < 0)
{
syslog(LOG_ERR, "Listen socket, bind() failed");
close(fd);
return false;
}
if (listen(fd, 5) < 0)
{
syslog(LOG_ERR, "Listen socket, listen() failed");
close(fd);
return false;
}
return true;
}
//FUNCTION: ***stringtosockaddr***
struct mysockaddr Socket::stringtosockaddr(std::string address)
{
struct sockaddr_in myname_in;
struct sockaddr_un myname_un;
struct mysockaddr myname;
memset(&myname_in, 0, sizeof(struct sockaddr_in));
memset(&myname_un, 0, sizeof(struct sockaddr_un));
memset(&myname, 0, sizeof(struct mysockaddr));
if (domain == AF_INET)
{
in_addr_t ip = INADDR_ANY; uint16_t port = 0;
char buffer[STRING_SIZE]; char *tmp;
strncpy(buffer, address.c_str(), STRING_SIZE);
tmp = strchr(buffer, ':');
if (tmp) { *tmp = '\0'; port = atol(tmp + 1); }
ip = inet_addr(buffer);
/* Resolve the name, if needed. */
if (ip == INADDR_NONE)
{
struct hostent *hostent = gethostbyname(buffer);
if (hostent) memcpy((char *) &ip, hostent->h_addr, sizeof(in_addr_t));
}
myname_in.sin_family = domain;
myname_in.sin_port = htons(port);
myname_in.sin_addr.s_addr = ip;
memcpy(&myname, &myname_in, sizeof(sockaddr_in));
}
else
{
myname_un.sun_family = domain;
strncpy(myname_un.sun_path, address.c_str(), UNIX_PATH_MAX);
memcpy(&myname, &myname_un, sizeof(sockaddr_un));
}
return myname;
}
//FUNCTION: ***awaitconnection***
bool Socket::awaitconnection(class Socket &clientsocket, std::string &clientaddress)
{
int newfd;
struct sockaddr_in clientsockaddr;
socklen_t clientsockaddrlen = sizeof(struct sockaddr_in);
if ((newfd = accept(fd, (struct sockaddr *) &clientsockaddr, &clientsockaddrlen)) < 0)
return false;
clientsocket.setfd(newfd);
clientaddress = sockaddrtostring((struct mysockaddr *) &clientsockaddr);
return true;
}
//FUNCTION: ***sockaddrtostring***
std::string Socket::sockaddrtostring(struct mysockaddr *pmyname)
{
struct sockaddr_in myname_in;
struct sockaddr_un myname_un;
std::string result;
memset(&myname_in, 0, sizeof(struct sockaddr_in));
memset(&myname_un, 0, sizeof(struct sockaddr_un));
if (pmyname->sa_family == AF_INET)
{
memcpy(&myname_in, pmyname, sizeof(struct sockaddr_in));
result = stringprintf("%s:%d", inet_ntoa(myname_in.sin_addr), ntohs(myname_in.sin_port));
}
else
{
memcpy(&myname_un, pmyname, sizeof(struct sockaddr_un));
result = myname_un.sun_path;
}
return result;
}
阅读(922) | 评论(0) | 转发(0) |