How to send nc similar command using python?

1.5k views Asked by At

I am trying to send parameter foo and its value to statsD using python (python-2.7) program. When I send packets from command line, using below netcat command, statsD gets value for foo:150 which is correct. echo "foo:150|c" | nc -u -w0 127.0.0.1 8125

However, when I send foo:150 through Python program, statsD is getting large random values for foo, instead of 150. Python program and statsD receive value output is below. Any idea what is error in python program that is causing statsD to receive random value, but working perfectly when sending through nc (netcat) command?

PYTHON PROGRAM:

import socket
import random
UDP_IP = "127.0.0.1"
UDP_PORT = 8125
while(True):

        MESSAGE = "foo:150|c"       
        #print "message:", MESSAGE

        sock = socket.socket(socket.AF_INET, # Internet
                             socket.SOCK_DGRAM) # UDP
        sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

StatsD received value:

timer_data: {},
  counter_rates:
   { 'statsd.bad_lines_seen': 0,
     'statsd.packets_received': 19828,
     'statsd.metrics_received': 19828,
      foo: 2974200 },
  sets: {},

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1

There are 1 answers

0
ghost204nit On BEST ANSWER

I figured out the answer. Seems like when I changed sending value from counter to as gauges, I am getting correct value. So, I think problem was not in my python program, but it is some logic in statsD that was giving me unexpected random values for foo when passing as part of counter.

So in short, when I did change from MESSAGE = "foo:150|c" to MESSAGE = "foo:150|g", I start getting correct value for foo. Below is the output:

{ counters:
   { 'statsd.bad_lines_seen': 0,
     'statsd.packets_received': 150383,
     'statsd.metrics_received': 150383 },
  timers: {},
  gauges: { foo: 150, 'statsd.timestamp_lag': 0 },
  timer_data: {},
  counter_rates:
   { 'statsd.bad_lines_seen': 0,
     'statsd.packets_received': 150383,
     'statsd.metrics_received': 150383 },
  sets: {},