Jose Thomas
Jose Thomas

Reputation: 566

Can't connect using setsockopt in python

I am new to python. So the question seems silly.

I want to implement a simple program for client and server in python.

The server.py is

import socket
#s = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, 25, "wlan0"+'\0')
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
    c,addr = s.accept()
    print "Got connection from",addr
    c.send("Thank you for connecting")
    c.close()

The client.py is

import socket
#s = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, 25, "wlan0"+'\0')
host = socket.gethostname()
port = 12345
s.connect((host,port))
print s.recv(1024)
s.close

The problem is that compiler is showing an error "operation is not permitted". I tried executing program as root. The error is gone, But client and server connection was not made.

Everything works fine before adding this line

   s.setsockopt(socket.SOL_SOCKET, 25, "wlan0"+'\0')

Hope somebody can aswer my problem. I want to connect client and server through wlan0 interface.

Thanks.

Upvotes: 2

Views: 1636

Answers (1)

dsgdfg
dsgdfg

Reputation: 1520

Server PY:

import socket
import fcntl
import struct
#s = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)




def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

host = get_ip_address("eth0")#replace with "wlan0"
port = 12345
s.bind((host,port))
s.listen(5)
while True:
    c,addr = s.accept()
    print "Got connection from",addr
    c.send("Thank you for connecting")
    c.close()

Client PY:

import socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

#s = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = get_ip_address("eth0")#replace with "wlan0"
port = 12345
s.connect((host,port))
print s.recv(1024)
s.close

check this. warning : Server py run on shell("python server.py") and client run on idle.

Upvotes: 1

Related Questions