I have written a socket in the android NDK and a server in c. It is able to connect to the server fine. However if the server is down or I try to get it to connect to a different random IP the call to connect still returns 0 when it should return -1.
Here is the code for the client:
#include <stdio.h> #include <jni.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <android/log.h> #include <unistd.h> #define APPNAME "MyApp" #define logcat(...) __android_log_print(ANDROID_LOG_VERBOSE, APPNAME, __VA_ARGS__) int createSocket() { int sockFD; if ((sockFD = socket(AF_INET, SOCK_STREAM, 0)) < 0) { logcat("Unable to create socket"); return -1; } logcat("Socket created: %i", sockFD); return sockFD; } JNIEXPORT jint JNICALL Java_myapp_client( JNIEnv* env, jobject thiz ) { struct sockaddr_in server; int sockFD, new_socket; char * message; if ((sockFD = createSocket()) < 0) { return -1; } server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr(server ip); server.sin_port = htons(8888); new_socket = connect(sockFD, (struct sockaddr *)&server, sizeof(server)); logcat("Connect return value: %i", new_socket); int rtn = recv(sockFD, message, sizeof(char), 0); logcat("Message: %i", rtn); close(sockFD); return 1; }
A valid descriptor is made for the socket, the return values for connect and recv are zero when I run this without my server running. Might be worth noting the android device is connected to the internet over mobile internet.