1import socket
2hostname = socket.gethostname()
3IPAddr = socket.gethostbyname(hostname)
4print("Your Computer Name is:" + hostname)
5print("Your Computer IP Address is:" + IPAddr)
6#How to get the IP address of a client using socket
1## importing socket module
2import socket
3## getting the hostname by socket.gethostname() method
4hostname = socket.gethostname()
5## getting the IP address using socket.gethostbyname() method
6ip_address = socket.gethostbyname(hostname)
7## printing the hostname and ip_address
8print(f"Hostname: {hostname}")
9print(f"IP Address: {ip_address}")
1import socket
2host_name = socket.gethostname()
3IPAddress = socket.gethostbyname(host_name)
4print("Your Computer Name is:" + host_name)
5print("Your Computer IP Address is:" + IPAddress)
6#How to get the IP address of a client using socket module
1#!/usr/bin/python # This is server.py file
2
3import socket # Import socket module
4
5s = socket.socket() # Create a socket object
6host = socket.gethostname() # Get local machine name
7port = 12345 # Reserve a port for your service.
8s.bind((host, port)) # Bind to the port
9
10s.listen(5) # Now wait for client connection.
11while True:
12 c, addr = s.accept() # Establish connection with client.
13 print 'Got connection from', addr
14 c.send('Thank you for connecting')
15 c.close() # Close the connection
1# If you are connected to the client socket you can get its address
2client_socket.getpeername()
3# Expected return value is a Tuple (ip, port)
4
5# You can also get your own socket address
6client_socket.getsockname()
7# Expected return value is a Tuple (ip, port)
11. Import the socket module.
22. Get the hostname using the socket.gethostname() method and store it in a variable.
33. Find the IP address by passing the hostname as an argument to the
4socket.gethostbyname() method and store it in a variable.
54. Print the IP address.