Skip to content

Instantly share code, notes, and snippets.

@mathslinux
Created June 28, 2013 05:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathslinux/5882699 to your computer and use it in GitHub Desktop.
Save mathslinux/5882699 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <gio/gio.h>
#include "ip.h"
static gchar *get_addr()
{
g_type_init();
GSocketClient *client = g_socket_client_new();
GSocketConnection *c = g_socket_client_connect_to_uri(
client, "http://cip.cc", 80, NULL, NULL);
if (c) {
GSocket *socket = NULL;
g_object_get(c, "socket", &socket, NULL);
if (socket) {
char buf[2048] = {0};
char *str = g_malloc0(1024);
char *p, *q;
char *send = "GET / HTTP/1.1\r\nUser-Agent: curl/7.29.0\r\nHost: cip.cc\r\nAccept: */*\r\n\r\n";
g_socket_send(socket, send, strlen(send) + 1, NULL, NULL);
g_socket_receive(socket, buf, sizeof(buf), NULL, NULL);
p = strstr(buf, "IP");
q = strstr(p, "\n");
if (p && q) {
char ip[32] = {0};
snprintf(ip, q - p + 2, "%s", p);
strcat(str, ip);
}
p = strstr(buf, "地址");
q = strstr(p, "\n");
if (p && q) {
char addr[1024] = {0};
snprintf(addr, q - p + 2, "%s", p);
strcat(str, addr);
}
g_socket_close(socket, NULL);
return str;
}
}
g_object_unref(client);
return NULL;
}
JNIEXPORT jstring JNICALL Java_org_mathslinux_glib_1demo_GetIPAddr_getAddr
(JNIEnv *je, jclass jc)
{
char *addr = get_addr();
return (*je)->NewStringUTF(je, addr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment