在C中,我尝试使用以下函数连接到服务器:
int clientConnect() {
//1. Set up connection address and port
char *ipAddress = SMSA_DEFAULT_IP;
int port = SMSA_DEFAULT_PORT;
//1a. Set up a sockaddr_in struct as described in lecture
struct sockaddr_in caddr;
caddr.sin_family = AF_INET;
caddr.sin_addr.s_addr = htonl(SMSA_DEFAULT_IP);
caddr.sin_port = htons( port );
//2. Create a socket
server_socket = socket(PF_INET, SOCK_STREAM, 0);
if(server_socket == -1)
{
logMessage(1, "There was an error creating a socket in clientConnect()");
return -1;
}
//3. Connect
if( connect(server_socket, (const struct sockaddr *)&caddr, sizeof(struct sockaddr) ) == -1)
{
logMessage(1, "There was an error connecting in clientConnect()");\
return -1;
}
logMessage(2, "The connection was made!");
return 0;}
调用此函数时,我会在日志There was an error connecting in clientConnect()
中收到一条消息。这是我第一次用C进行网络编程,所以我怀疑我错过了什么。
答案 0 :(得分:0)
connect
的最后一个参数应为sizeof caddr
:
connect(server_socket, (const struct sockaddr *)&caddr, sizeof caddr);