-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket_programming.py
More file actions
34 lines (27 loc) · 1.03 KB
/
Copy pathsocket_programming.py
File metadata and controls
34 lines (27 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# An example script to connect to Google using socket
# programming in Python
# for socket
import socket
import sys
try:
# socket.AF_INET --> specifies that this is an internet socket,
# socket.SOCK_STREAM --> specifies that this is an TCP connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket successfully created")
except socket.error as err:
print("socket creation failed with error %s" % err)
# default port for socket
port = 80
try:
# host_ip = socket.gethostbyname(socket.gethostname()) --> this command will automatically retrieve the
# ip address of the running computer.
# do not use above command if there is virtual box installed on the system, since the above command takes
# ip address of the VM instead of the system.
host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
# this means could not resolve the host
print("there was an error resolving the host")
sys.exit()
# connecting to the server
s.connect((host_ip, port))
print("the socket has successfully connected to google")