Java Examples - Connecting to a Specified Host with Socket
The following example demonstrates how to use the getInetAddress() method of the net.Socket class to connect to a specified host:
Main.java File
import
java
.
net
.
InetAddress
;
import
java
.
net
.
Socket
;
public
class
WebPing
{
public
static
void
main
(
String
[
]
args
)
{
try
{
InetAddress
addr
;
Socket
sock
=
new
Socket
(
"
www.runoob.com
"
,
80
)
;
addr
=
sock
.
getInetAddress
(
)
;
System
.
out
.
println
(
"
Connected to
"
addr
)
;
sock
.
close
(
)
;
}
catch
(
java
.
io
.
IOException
e
)
{
System
.
out
.
println
(
"
Unable to connect
"
args
[
0
]
)
;
System
.
out
.
println
(
e
)
;
}
}
}
The output of the above code is:
连接到 http:/www.runoob.com/222.73.134.120
Java Examples