我创建了旨在将新套接字绑定到计算机地址的代码,以侦听特定端口上的传入连接。我正在使用 getaddrinfo。这是最好的方法吗?将端口整数转换为字符串似乎毫无意义。有没有不需要 sprintf 的方法来做到这一点?
bool CBSocketBind(void * socketID,u_int16_t port){
struct addrinfo hints,*res,*ptr;
int socketIDInt;
// Set hints for the computer's addresses.
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
// Get host for listening
char portStr[6];
sprintf(portStr, "%u",port);
if (getaddrinfo(NULL, portStr, &hints, &res) != 0)
return false;
// Attempt to bind to one of the addresses.
for(ptr = res; ptr != NULL; ptr = ptr->ai_next) {
if ((socketIDInt = socket(ptr->ai_family, ptr->ai_socktype,ptr->ai_protocol)) == -1)
continue;
if (bind(socketIDInt, ptr->ai_addr, ptr->ai_addrlen) == -1) {
close(socketIDInt);
continue;
}
break; // Success.
}
freeaddrinfo(res);
if (ptr == NULL) // Failure
return false;
socketID = malloc(sizeof(int));
*(int *)socketID = socketIDInt; // Set socket ID
// Make socket non-blocking
fcntl(socketIDInt,F_SETFL,fcntl(socketIDInt,F_GETFL,0) | O_NONBLOCK);
return true;
}