Sockets in Python:

I am a novice. Two weeks ago I never through about network programming and 24 hours ago, I din’t know exactly what a socket was. Bear with me!

  • reads in input from the network and saves it to a file.

I have made a rudimentary code that uses Pyshark but I want to try and use the socket module.

I went to the documentation and read through it. Then I just copied and pasted this code:

import socket

# the public network interface
HOST = socket.gethostbyname(socket.gethostname())

# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))

# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

# receive a package
print(s.recvfrom(65565))

# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

I got this when I tried to run the above code in Pycharm:

_sock = _realsocket(family, type, proto)
socket.error: [Errno 1] Operation not permitted

After I did a bit of research, I realized it was because I did not have root access. Because I work on a Mac, it was a bit annoying to get root access. In fact, the directions on the apple website did not work for my El Captain software (womp!) so I just gave up. A way around it is to run the python code in the terminal using sudo before each run command.

Then, I got this:

AttributeError: ‘_socketobject’ object has no attribute ‘ioctl’

At this point I realized I should try and figure out what exactly is going on so I simplified the code to this:

import socket

# the public network interface
HOST = socket.gethostbyname(socket.gethostname())

# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
print s.recvfrom(6556500)

When I ran this, I got a raw socket output (I think that is the terminology)

Veras-MacBook-Pro:~ DragonQueen$ sudo python /Users/DragonQueen/PycharmProjects/PythonKicks/Pyshark\ Playground/Playgound1.py
(‘E\x00$\x00\xb9]\x00\x00\xf9\x01X:\n2\x00)F#_\xaf\x0b\x00\xae\xb3\x00\x00\x00\x00E\x00@\x00q[@\x00\x01\x06W\x80F#_\xaf\n\x00\x01\x0b\xd0\x98\x1bX\x9e\xcd\xbb\x8d’, (‘10.50.0.41’, 0))

At least I got something.

My next step was to learn what I could do with sockets. I went online and looked. I found a youTube video that helped me get to know the basics of functionality very well. I did the tutorial and ran it beautifully in my terminal.

The youTuber, Draps, used socket to create client side and server side programs.

With this information I was able to start building my program to write in the inputs inside a file.

So I created a Frankenstein’s Monster type code with snippets of the server side code and tried to use the client side code he wrote to check that my server is working the way it’s supposed to.

Then I ran into another problem. When I tried to run another program using the same port as the program I got from Drap’s, I kept getting this:

socket.error: [Errno 48] Address already in use

Nooooooo! Again I went to google. It turns out, for some reason, the socket never closed after I opened it. Working on a mac, there was no definantive documentation because it varies so wildly. Since I am just beginning to get comfortable using the terminal, I panicked!

After taking a deep breadth I realized I just had to try anything I found on the internet. I did find a way to check if a port is open and close it.

Putting lsof -i :(insert port #) gives you this lovely chart. Notice, the header:

COMMAND, PID, USER, TYPE, DEVICE SIZE/OFF, NODE, NAME

under PID is the PID number which you will need to locate the process using the port and shut it down.

Using this number, you put in this command:

: kill -9 1239

Then you can use the lsof command to check to see if it is still open. It should do nothing.

After all of this, I ran into another problem almost immediately. I kept getting:

socket.error: [Errno 61] Connection refused

Ugh! Back to google. But this time it did not help. So I looked at my code and realized three things;

  • The client and server side socket had two different ports.. oops
  • I fudged around with the ip address of one of the host on the server side.
  • I kept running the client side before the server. Derp!

After I fixed these things and went through the ports I have used to close them down (for good measure)…. It worked!

Now I can input data of the client side and have it saved to a text file.

Server Side

import socket

def Main():
out_string = ""
# set up host on my own computer
    host = '127.0.0.1'
port = 5002
#create socket obj
s = socket.socket()
# bind socket to port @ host, port
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
while True:
data = c.recv(1024)
out_file = open("Client_Data.txt", "w")
out_string += str(data)
out_string += "\n"
out_file.write(out_string)
if not data:
break

print
str(data)
c.send(" Wubalabadubdub!!!!")
s.close()
if __name__ == '__main__':
Main()

Client side:

import socket
#Watch Draps' video liked to above id you have any questions
def Main():
host = '127.0.0.1'
port = 5002
s= socket.socket()
s.connect((host,port))
message = raw_input("please put message")
while message != "q":
s.send(message)
data = s.recv(1024)
print "received from server: " + str(data)
message = raw_input("please put message")
s.close()





if __name__ == '__main__':
Main()
The terminal conversation I had with myself
Client_Date.txt file created on the server side

I’m sorry it was a bit long winded but I do write these while I am learning. It is not meant to be a tutorial more like a study session. I kindly omitted the times by program crashed because I forgot to capitalize or something. Please comment if you see something wrong, cool, or funny. *Please don’t be rude*. I’d also love to hear about what you guys are doing.