1 /* 2 * Copyright 2021 Google LLC 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 <arpa/inet.h> 18 #include <netinet/in.h> 19 #include <stdio.h> 20 #include <sys/socket.h> 21 22 int main(int argc, char* argv[]) 23 { 24 if (argc < 1) 25 { 26 return 1; 27 } 28 if (argc != 2) 29 { 30 fprintf(stderr, "Usage: %s <ip address>\n", argv[0]); 31 return 1; 32 } 33 34 union 35 { 36 struct in_addr in; 37 struct in6_addr in6; 38 } buf; 39 int af = AF_INET6; 40 if (inet_pton(af, argv[1], &buf) != 1) 41 { 42 af = AF_INET; 43 if (inet_pton(af, argv[1], &buf) != 1) 44 { 45 fprintf(stderr, "Invalid IP Address: %s\n", argv[1]); 46 return 2; 47 } 48 } 49 50 char str[INET6_ADDRSTRLEN]; 51 if (inet_ntop(af, &buf, str, sizeof(str)) == NULL) 52 { 53 return 1; 54 } 55 56 printf("%s\n", str); 57 return 0; 58 } 59