如何将serversocket绑定到特定的IP? [英] How can I bind serversocket to specific IP?

查看:1006
本文介绍了如何将serversocket绑定到特定的IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有字符串表示IP地址(IPv4或IPv6),我该如何创建 ServerSocket 和绑定到这个IP而不关心IP是否传入,是IPv4还是IPv6?

我看到有一个构造函数: ServerSocket(int port,int backlog,InetAddress bindAddr)的InetAddress 似乎没有提供任何构造函数和它的子类必须特定于IPv4和IPv6的名字。点击
所以怎么可以将套接字绑定到IP?

If I have a String representing an IP address (IPv4 or IPv6) how can I create a ServerSocket and bind to this IP without caring if the IP passed in, is IPv4 or IPv6?
I see that there is a constructor:ServerSocket(int port, int backlog, InetAddress bindAddr) but InetAddress does not seem to offer any constructors and its subclasses have names specific to IPv4 and IPv6.
So how can I bind the socket to the IP?

推荐答案

可以使用工厂方法 INetAddress.getByName 。它将找出要使用的子类。例如:

You can use the factory method INetAddress.getByName. It'll figure out which subclass to use. For example:

InetAddress addr = InetAddress.getByName("127.0.0.1");
// or
InetAddress addr = InetAddress.getByName("::1");

// and now you can pass it to your socket-constructor
ServerSocket sock = new ServerSocket(1234, 50, addr);

这篇关于如何将serversocket绑定到特定的IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆