class test{
static void Split(string ip,out string str1)
{
int i=ip.length
while(i>0)
{
char ch=ip[i-1]
if(ch==':')
break
i--
}
str1=ip.Substring(0,i)
}
static void Main()
{
string str1
Split("192.168.0.255:8080",out str1)
Console.WriteLine("{0}",str1)
}
}
str1中保存的就是你的ip,192.168.0.255
获取本机ip地址InetAddress addr = InetAddress.getLocalHost()
ip=addr.getHostAddress().toString
socket.connect(new InetSocketAddress(ip, port), timeout)
看有没有抛异常 没异常就是已经连接上了
想获取服务器名称 可以用ARP协议 或者测试连接的时候服务器回应一个名称
package baiduzhidaoimport java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
public class Client {
public static void main(String[] args) {
/**
* 端口号
*/
int port = 10000
/**
* 连接延时
*/
int timeout = 300
System.out.println("Scanner Start...")
Socket socket
/**
* 扫描
*/
for (int i = 1, k = 254 i < k i++) {
if ((socket = isOnLine("192.168.1." + i, port, timeout)) != null) {
System.out.println("Server:"
+ socket.getInetAddress().getHostAddress()
+ ":" + socket.getPort() + " Is Waiting...")
}
/**
* 关闭连接
*/
if (socket != null && !socket.isClosed()) {
try {
socket.close()
} catch (IOException e) {
socket = null
}
}
}
System.out.println("Scanner end...")
}
/**
* 测试连接服务器,返回连接成功后的Socket
*
* @param ip
* 服务器Ip
* @param port
* 服务器端口号
* @param timeout
* 连接延时
* @return 返回连接成功后的Socket
*/
private static Socket isOnLine(String ip, int port, int timeout) {
Socket socket = new Socket()
try {
socket.connect(new InetSocketAddress(ip, port), timeout)
} catch (IOException e) {
return null
}
return socket
}
}
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)