54

Python is often described as a "batteries included" kind of language, and this is no exception. There's a module just for IP address manipulation and another module to generate random numbers. Put together, they do exactly what you want, in a way that's slightly more readable (IMO). For this example, I'll assume that the variable v contains either 4 or 6. ...


34

I think it's very strange that you provide iterators and an operator[] for an IP address. Generally speaking, IP addresses are not considered to be "iterable"; an IP address is just a single address. If you were modeling a subnet mask, like 127.0.0.0/8, then it might make sense to model it as a range of addresses; but if you're modeling just a single address,...


32

Is there a faster way of accomplishing this? Would Multithreading/Multiprocessing speed things up? Any help or other feedback would be much appreciated! No, for the most part, multi-threading will make no difference for you. At some point the bottleneck should be the IO speed of reading 50GB of file content, and not the speed of the processing. You also ...


31

Python has a philosophy of "Batteries Included". Don't reinvent what's in the standard library! In particular, this code is much more easily written if we take advantage of IPv6Address: import ipaddress address = input('Please enter an IP address: ') try: addr = ipaddress.IPv6Address(address) except ipaddress.AddressValueError: print(address, '...


27

You can change valid_characters to a string. 'ABCDEFabcdef:0123456789'. You can use for element in elements: rather than: for i in range(len(elements)): element = elements[i] You can use in rather than manually perform the check. if current in valid_characters: is_valid.append(1) You can use a list comprehension, rather than manually build a list....


26

Here are a few ideas about your code. Check for command line arguments The code fails with an exception if it's invoked with no command line arguments because it attempts to use argv[1] and there isn't any. I'd suggest that it would be nice to print a "usage" message if the user enters either an invalid or no argument. Use a list comprehension List ...


19

preface: This answer is more of a design/architecture related meta-answer about this type of check and might be seen as missing the point of a code review by some. QUESTIONS about design and architecture are off-topic, but I can't find any meta discussions about ANSWERS that address these. I think a generic IsInternetAvailable check misses the point. 99% of ...


19

For someone not familiar with Python, you have picked pretty good habits. Not everyone uses functions or the if __name__ == '__main__' guard first try. That being said, I think it would make more sense to provide 2 functions instead of a single one: random_ipv4 and random_ipv6. You could also feed generator expressions to join. They are both faster to ...


18

I wouldn't both prefixing 'internal' functions with an underscore. Instead, just put this in a module, and only export the functions you want to export. If you care about following the node style guide, you should know that node suggests ignoring Crockford's fetish for one var declaration. Note: this is pretty controversial. I'm not a fan of var ...


14

Check for invalid outputs, and regenerate them. It's possible that you'll produce an output that's reserved for a particular purpose, such as loopback (127.0.0.1 or ::1) or broadcast (255.255.255.255, ff02::1, ff02::2). Build in knowledge of such addresses, and if you find you've produced one, then replace it. You can do that recursively: def ...


13

It seems fine if there is not any simpler Java or Apache Commons API. I'd modify a few small things: The isValid boolean would be unnecesary if you return immediately when you know the return value. (Flattening Arrow Code) (address == null || address.trim().isEmpty()) could be changed to StringUtils.isBlank. According to the Code Conventions for the Java ...


13

I would use a different service that provides output in a format that is good for tools (not humans (html is for displaying for humans)). Hit this url: https://ifconfig.co/json You're output looks like this: { "ip": "154.140.296.288", "ip_decimal": 926648668, "country": "United States", "city": "Seattle", "hostname": "154-140-296-288.Bob.com" } ...


13

You storing the value in std::array<value_type, 4> which is fine. But if you change your mind on the storage type you have to change this in like 10 places. To make this easier it is a good idea to abstract the storage type and then use this storage type in all places. using Storage = std::array<value_type, 4>; using ...


12

Your bitwise operations are fine, though the >>> right-shifts are unnecessary. @Lucien and @Corbin are right! The right-shift operators prevent (128 << 24) from being interpreted as a negative number. The rest of the code is fine too, but a bit long for my taste. Personally, I'd use a long regular expression to do all the parsing and ...


12

Validate the input: At present, your program aborts with IndexError if called without arguments, aborts with ValueError if called with a non-integer argument, prints None if called with an integer argument that is not 4 or 6. Missing or invalid arguments should print a helpful error message. Most Unix command-line tools print the message to the standard ...


11

def validateIP(ip): I would expect a name starting is (a useful hint that it returns a Boolean rather than some more complex validation data structure) and explicitly mentioning IP v4 (since the current name is misleading). E.g. is_valid_IPv4_address. #split them by '.' , and store them in an array #check the array if the length is 4 length arr = ip....


10

The class WebClient implements IDisposable so it should be disposed after we are finished with it. An excellent way to do that is to use the using statement: string ncsi; using (var client = new WebClient()) { ncsi = client.DownloadString("http://www.msftncsi.com/ncsi.txt"); }


10

Your code is fine, except for the stray method. POST at that point isn't valid, and you will try to connect to a server called POST. Just try your curl call with -Iv, you will notice two connections: curl -Iv POST whatismyip.org If you want to use the method, you would have to write -x POST, but to just get information, you use -x GET (which is the default ...


10

Various comments in no specific order. The 2 last statements are identical, thus it is not relevant to check invalid_segment. You could write: if len(address) == len(is_valid) and len(address_list) == 8 and invalid_segment == False: print("It is a valid IPv6 address.") else: print("It is not a valid IPv6 address.") It would be clearer to write a ...


9

Your parsing of IPv4 addresses is not incorrect, since it succeeds at parsing IPv4 addresses in dotted-quad notation as specified in RFC 810. However, you may be interested to know that the inet_aton() function in Unix is more lenient, supporting some unconventional forms: 1 : 0. 0. 0. 1 127.1 : 127. 0. 0. 1 192.168.1 : 192.168. 0. 1 ...


9

You're passing fundamental types by const reference. These are better off just being passed by value. So you'd get things like explicit address(uint32_t value); reference operator[](int index) noexcept(false); Your prefix increment and decrement operators should return a reference to the incremented value. address &operator++() { /* ... */ return *...


9

<stdbool.h> Unless you need compatibility with C89 for some reason, I would use bool for the return type of the function and true and false as the possible values. It helps readability. sscanf() This one depends on your performance needs. A solution using sscanf() will be much easier to understand with a simple look and also shorter in code, but ...


8

You can use the InetAddressUtils from httpclient library: /** * @param ip the ip * @return check if the ip is valid ipv4 or ipv6 */ private static boolean isValidIp(final String ip) { return InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip); }


8

First off, a couple of quick tips: Follow the PEP8 style guide Instead of x == False, use not x, for example in if (is_legal_ip(args.ip_port[0]) == False) Omit unnecessary imports (import socket in this example) Use spaces around operators, for example all(0 <= int(p) < 256 for p in pieces) Break lines after colons, for example in if __name__ == "...


8

public class IpHelpers Your class has only static methods but it's not marked as static, you should change it to public static class IpHelpers. It'll prevent to accidently forget to add static in some methods. Your first public function: public static string IpToHex(string ip, bool padIp) In my opinion it has these issues: You accept IP address as ...


8

According to the Wikipedia article on IPv6 addresses, there are alternative ways of representing IPv6 addresses that you are not taking into account with this approach: Leading zeroes in a group may be omitted, but each group must retain at least one hexadecimal digit. ... One or more consecutive groups containing zeros only may be replaced with a ...


8

Since you already got a couple of answers telling you to validate your inputs, here is a way how to do it using the argparse module: import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-v', type=int, choices=(4, 6), default=4, ...


8

A doc string reads nicer then # blockcomments Consider making a doc string of that function, so you can do help(validate_ip) and it will print the doc string in the interpreter. Adhere to PEP8 Functions and variables should be snake_case ie def validate_ip(ip): You could use the all keyword to check if each part is correct; this will return False for the ...


7

It took me a while until I understood your range notation. Consider switching to CIDR syntax. Networks are routed using CIDR so you usually can express ownership of an IP address by CIDR notation. Another thing to note is that your code does not support IPv6. IPv6 will become more and more important over the next years. I recommend supporting it right now ...


7

That's nutty, trying to address a server by a changing IP address. Reconfiguring the wiki to adjust to it is even crazier. The standard practice for adapting to dynamic IP addresses is to use a dynamic DNS service. Then, everything else works normally. Pick a hostname, like afuna.noip.com. Run a DDNS client to register your hostname whenever you acquire a ...


Only top voted, non community-wiki answers of a minimum length are eligible