blob: 1d702fca6ca61f0b4a829dfe0de58c977bd01cfe [file] [log] [blame]
Chia-chi Yeh4c5d28c2010-08-06 14:12:05 +08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <string.h>
19#include <arpa/inet.h>
20#include <netinet/in.h>
21
22#include "jni.h"
23#include "JNIHelp.h"
24
25int parse(JNIEnv *env, jstring jAddress, int port, sockaddr_storage *ss)
26{
27 if (!jAddress) {
28 jniThrowNullPointerException(env, "address");
29 return -1;
30 }
31 if (port < 0 || port > 65535) {
32 jniThrowException(env, "java/lang/IllegalArgumentException", "port");
33 return -1;
34 }
35 const char *address = env->GetStringUTFChars(jAddress, NULL);
36 if (!address) {
37 // Exception already thrown.
38 return -1;
39 }
40 memset(ss, 0, sizeof(*ss));
41
42 sockaddr_in *sin = (sockaddr_in *)ss;
43 if (inet_pton(AF_INET, address, &(sin->sin_addr)) > 0) {
44 sin->sin_family = AF_INET;
45 sin->sin_port = htons(port);
46 env->ReleaseStringUTFChars(jAddress, address);
47 return 0;
48 }
49
50 sockaddr_in6 *sin6 = (sockaddr_in6 *)ss;
51 if (inet_pton(AF_INET6, address, &(sin6->sin6_addr)) > 0) {
52 sin6->sin6_family = AF_INET6;
53 sin6->sin6_port = htons(port);
54 env->ReleaseStringUTFChars(jAddress, address);
55 return 0;
56 }
57
58 env->ReleaseStringUTFChars(jAddress, address);
59 jniThrowException(env, "java/lang/IllegalArgumentException", "address");
60 return -1;
61}