I wrote a socket program to send a file and receive a string from socket In which I specified the client(wrote the ip address of client) I want to get that client address dynamically, I tried .getpeername() function but getting error
I tried .getpeername() function but getting error
#host = '10.66.227.181' # fixed ip of one client only
client_socket = socket.socket()
host = client_socket.getpeername()
print(clientip)
port = 8000
print(host,port)
client_socket.connect(host,port)
clientip = socket.gethostname(client_socket.getpeername()) OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
In the standard Internet protocols TCP and UDP, a socket address is the combination of an IP address and a port number, much like one end of a telephone connection is the combination of a phone number and a particular extension.
If a UDP socket isn't connected there is no peer. So there can't be a peer name. And if it is connected, you already know how you connected it to.
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(host,port)
host, port = client_socket.getpeername()
Here is the example from the book 'Foundations of Python Network Programming' about udp sockets(both server and client side) and I think this example will be useful for you:
import argparse, socket
from datetime import datetime
MAX_BYTES = 65535
def server(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('127.0.0.1', port))
print('Listening at {}'.format(sock.getsockname()))
while True:
data, address = sock.recvfrom(MAX_BYTES)
text = data.decode('ascii')
print('The client at {} says {!r}'.format(address, text))
text = 'Your data was {} bytes long'.format(len(data))
data = text.encode('ascii')
sock.sendto(data, address)
def client(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
text = 'The time is {}'.format(datetime.now())
data = text.encode('ascii')
sock.sendto(data, ('127.0.0.1', port))
print('The OS assigned me the address {}'.format(sock.getsockname()))
data, address = sock.recvfrom(MAX_BYTES) # Danger! See Chapter 2
text = data.decode('ascii')
print('The server {} replied {!r}'.format(address, text))
if __name__ == '__main__':
choices = {'client': client, 'server': server}
parser = argparse.ArgumentParser(description='Send and receive UDP locally')
parser.add_argument('role', choices=choices, help='which role to play')
parser.add_argument('-p', metavar='PORT', type=int, default=1060,
help='UDP port (default 1060)')
args = parser.parse_args()
function = choices[args.role]
function(args.p)
source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With