t sockaddr_in serv_addr;
if ((servrec = getservbyname(servicename, "tcp")) == NULL) {
return(-1);
}
bzero((char *)&Mysock, sizeof(Sockets));
Mysock.Port = servrec->s_port; /* Service Port in Network Byte Order */
if((mainsock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return(-2);
}
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* 任意网络接口 */
serv_addr.sin_port = servrec->s_port;
if (bind(mainsock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
close(mainsock);
return(-3);
}
if (listen(mainsock, 5) == -1) { /* 将主动套接字变为被动套接字,准备好接收连接 */
close(mainsock);
return(-4);
}
/* Set this socket as a Non-blocking socket. */
if (ioctl(mainsock, FIONBIO, &flag) == -1) {
close(mainsock);
return(-5);
}
Mysock.DaemonSock = mainsock;
FD_SET(mainsock, &Mysock.readfds); /* 申明对主套接字"可读"感兴趣 */
FD_SET(mainsock, &Mysock.exceptfds); /* 申明对主套接字上例外事件感兴趣 */
return(1);
}
void CloseMainSock()
/* 关闭主套接字,并清除对它上面事件的申明。在程序结束前关闭主套接字是一个好习惯 */
{
close(Mysock.DaemonSock);
FD_CLR(Mysock.DaemonSock, &Mysock.readfds);
FD_CLR(Mysock.DaemonSock, &Mysock.exceptfds);
}
int CreateConnection(struct in_addr *sin_addr)
/* Create a Connection to remote host which IP address is in sin_addr.
Param: sin_addr indicates the IP address in Network Byte Order.
if succeed return the socket number which indicates this connection,
else return error code (<0) */
{
struct sockaddr_in server; /* server address */
int tmpsock, flag=1, i;
if ((tmpsock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return(-1);
server.sin_family = AF_INET;
server.sin_port = Mysock.Port;
server.sin_addr.s_addr = sin_addr->s_addr;
/* Set this socket as a Non-blocking socket. */
if (ioctl(tmpsock, FIONBIO, &flag) == -1) {
close(tmpsock);
return(-2);
}
/* Connect to the server. */
if (connect(tmpsock, (struct sockaddr *)&server, sizeof(server)) < 0) {
if ((errno != EWOULDBLOCK) && (errno != EINPROGRESS)) {
/* 如果错误代码是EWOULDBLOCK和EINPROGRESS,则不用关闭套接字,因为系统将在之后继续为套接字建立连接,连接是否建立成功可用select()函数来检测套接字是否"可写"来确定。*/
close(tmpsock);
return(-3); /* Connect error. */
}
}
FD_SET(tmpsock, &Mysock.readfds);
FD_SET(tmpsock, &Mysock.writefds);
FD_SET(tmpsock, &Mysock.exceptfds);
i = 0;
while (Mysock.Sockets[i] != 0) i++; /* look for a blank sockets position */
if (i >= 64) {
close(tmpsock);
return(-4); /* too many connections */
}
Mysock.Sockets[i] = tmpsock;
Mysock.SockNum++;
return(i);
}
int AcceptConnection(struct in_addr *IPaddr)
/* Accept a connection. If succeed, return the data sockets number, else return -1. */
{
int newsock, len, flag=1, i;
struct sockaddr_in addr;
len = sizeof(addr);
bzero((char *)&addr, len);<
socket编程原理(七)
最新推荐文章于 2024-07-18 17:37:17 发布