connect() C method in Android
H!
I have source in C, which is use the connect(peer->fd, (struct sockaddr *)dst->sockaddr, sizeof(struct sockaddr_in));
C method. I use the NDK and make the jni.
My application is a msrp modul, which contain a server and a client. This method is part of the client.
The source fragment:
/* We're going to be the client, connect to the other peer */
dst->sockaddr = calloc(1, sizeof(dst->sockaddr));
dst->sockaddr->sin_family = AF_INET;
dst->sockaddr->sin_port = htons(dst->port);
if(inet_aton(dst->address, &(dst->sockaddr->sin_addr)) == 0) { /* Not a numeric IP... */
struct hostent *host = gethostbyname(dst->address); /* ...resolve name */
if(!host) {
local_events(MSRP_ERROR, "Invalid host for address %s",
dst->address ? dst->address : "???.???.???.???");
return -1;
}
dst->sockaddr->sin_addr = *(struct in_addr *)host->h_addr_list;
}
printf("----[msrp_peer_connect]---- dst->sockaddr->sin_family: %d\n", dst->sockaddr->sin_family);
printf("----[msrp_peer_connect]---- dst->sockaddr->sin_port: %d\n", dst->sockaddr->sin_port);
printf("----[msrp_peer_connect]---- address_lenght: %d\n", sizeof(struct sockaddr_in));
printf("----[msrp_peer_connect]---- socket description: %d\n", peer->fd);
if(connect(peer->fd, (struct sockaddr *)dst->sockaddr, sizeof(struct sockaddr_in)) address, dst->port);
return -1;
}
and the result:
----[msrp_peer_connect]---- dst->sockaddr->sin_family: 2
----[msrp_peer_connect]---- dst->sockaddr->sin_port: 34330
----[msrp_peer_con开发者_如何学Cnect]---- address_lenght: 16
----[msrp_peer_connect]---- socket description: 5
I added the in the AndroidManifest.xml.
The original source code: libmsrp
Thanks
Check your if syntax :
if(connect(peer->fd,
(struct sockaddr *)dst->sockaddr,
sizeof(struct sockaddr_in)
)
address, dst->port);
return -1;
}
There shouldn't be any semicolon at the end of the if condition. If this code ever compiles, then it will always returns -1.
Also check your indentation. It's all wrong. It could be hiding bugs, because we don't know what the last curly brace could be closing, and anyway it makes your code hard to read.
And finally, you shouldn't fail silently.
if(connect(peer->fd,
(struct sockaddr *)dst->sockaddr,
sizeof(struct sockaddr_in) == -1) {
perror("---- [msrp_peer_connect]---- connect() failed");
return -1;
}
精彩评论