How to make a ping client in Python socket?
Question: I learn Python and as a practice decided to write a server for a network game
"Backgammon". The question arose as to make sure that found in the queue
apponet still online? How to send a ping and accept the answer? I'm trying to
do it on line 71, but this is incorrect.

    
    
    import pymongo, socket, threading, string, json, MySQLdb, random, time
    stat = True
    conn = {}
    #gamers = {}
    games = {}
    diceroll = []
    tempconn = {}
    
    c = pymongo.Connection()
    db = c.nardy
    nru = db.notregusers
    uwait = db.userwait
    
    class ClientThread(threading.Thread):
    
        def __init__(self, channel, details):
            self.channel = channel
            self.details = details
            threading.Thread.__init__(self)
    
        def getUserId(self, data):
            json_data = json.loads(data)
            if json_data['t'] == 'n':
                print ' - User not register'
                if nru.find({'identuser':json_data['i'], 'platform':json_data['p']}).count() == 0:
                    print ' - New user'
                    count = nru.find().count();
                    newid = count + 1;
                    nru.save({'id':newid, 'identuser':json_data['i'], 'platform':json_data['p'], 'level':1})
                    return nru.find_one({'id':newid})
                else:
                   print ' - Old user'
                   return nru.find_one({'identuser':json_data['i'], 'platform':json_data['p']})
            elif json_data['t'] == 'r':
                return 9999
    
        def mySQLConnect(self):
            db = MySQLdb.connect(host="localhost", user="", passwd="", db="", charset='utf8')
            return db
    
        def run(self):
            while True:
                data = self.channel.recv(1024)
                try:
                    json_data = json.loads(data)                
                    comm = json_data['c']
                    if comm == 'x':
                        if conn.has_key(gamer['level']) and self in conn[gamer['level']]:
                            conn[gamer['level']].remove(self)
                        self.channel.close()
                        break
                    elif comm == 'h':
                        gamer = self.getUserId(data)
                        self.gamer = gamer
                    elif comm == 'f':
                        lev = 0
                        findenemy = 1
                        while findenemy == 1:
                            if conn.has_key(gamer['level']):
                                lev = gamer['level']
                            elif conn.has_key((gamer['level'] - 1)):
                                lev = (gamer['level'] - 1)
                            elif conn.has_key((gamer['level'] + 1)):
                                lev = (gamer['level'] + 1)
                            if lev != 0:
                                if len(conn[lev]) > 0:
                                    enemy = conn[lev].pop(0)
                                    firsttime = time.time()
                                    enemy.channel.send('{"o":"p"}')
    
                                    while (firsttime + 30) > time.time() and findenemy == 1:
                                        if comm == 'k':
                                            findenemy = 0
                                            print ' - Ping enemy: ok'
    
    
                                    if findenemy == 0:
                                        self.enemy = enemy
                                        gameid = str(self.gamer['id']) + '_' + str(self.enemy.gamer['id'])
                                        games[gameid] = {'dice':[], 'nextstep':0}
                                        vrag = self.enemy
                                        a = random.sample(range(1,7),2)
                                        self.channel.send('{"o":"s", "u":"' + str(a[0]) + '", "e":"' + str(a[1]) + '"}')
                                        vrag.channel.send('{"o":"s", "u":"' + str(a[1]) + '", "e":"' + str(a[0]) + '"}')
                                        if a[0] > a[1]:
                                            step = 1
                                            games[gameid]['nextstep'] = self.gamer['id']
                                            self.channel.send('{"o":"u"}')
                                            vrag.channel.send('{"o":"w"}')
                                        else:
                                            step = 2
                                            games[gameid]['nextstep'] = self.enemy.gamer['id']
                                            self.channel.send('{"o":"w"}')
                                            vrag.channel.send('{"o":"u"}')
                                        tempconn[self.enemy] = self
                                else:
                                    conn[lev].append(self)
                                    findenemy = 0
                                    self.channel.send('{"o":"q"}')
                            else:
                                conn[gamer['level']] = [self]
                                self.channel.send('{"o":"q"}')
                    elif comm == 'w':
                        if not hasattr(self, 'enemy'):
                            self.enemy = tempconn[self]
                            vrag = self.enemy
                            gameid = str(self.enemy.gamer['id']) + '_' + str(self.gamer['id'])
                        self.channel.send('{"o":"o"}')
                    elif comm == 'r' and games[gameid]['nextstep'] == self.gamer['id']:
                        dice = []
                        dice.append(self.gamer['id'])
                        dice.append(random.randint(1,6))
                        dice.append(random.randint(1,6))
                        games[gameid]['dice'].append(dice)
                        self.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
                        vrag.channel.send('{"o":"r", "f":"' + str(dice[1]) + '", "s":"' + str(dice[2]) + '"}')
                        games[gameid]['nextstep'] = self.enemy.gamer['id']
                    elif comm == 'r' and games[gameid]['nextstep'] != self.gamer['id']:
                        self.channel.send('{"o":"w"}')
                    elif comm == 'm' and 't' in json_data:
                        self.channel.send('{"o":"y", "t":"' + str(json_data['text']) + '"}')
                        vrag.channel.send('{"o":"e", "t":"' + str(json_data['text']) + '"}')
                    elif comm == 's':
                        self.channel.send('{"o":"g", "countgame":"' + str(len(games)) + '"}')
                    elif comm == 'q' and 's' in json_data and 'e' in json_data:
                        print " - Player step"
                    elif comm == 'b' and self in conn[gamer['level']]:
                        conn[gamer['level']].remove(self)
    
                except ValueError:
                    continue
            print 'Closed connection:', self.details[0]
    
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('127.0.0.1', 8088))
    server.listen(5)
    
    while stat:
        channel, details = server.accept()
        ClientThread(channel, details).start()
    

Perhaps, in addition to answering the question, you give me some
recommendations ...


Answer: There are two options for you to send out a ping and get response.

  1. Use `scapy`. Use `sendp` function to send a ping and get response.
  2. Use `os.system` to invoke command line to send a ping and get response. Like `os.system('ping 127.0.0.1')`

Hope it helps.:)

