Python error ValueError: Unknown network interface None - python

import scapy.all as scapy
import requests
import json
This code work with API for getting information about venders
def vender_finding(mac_adr):
mac_url = 'http://macvendors.co/api/%s'
vender = (requests.get(mac_url % mac_adr))
response_dict = json.loads(json.dumps(vender.json()))
return response_dict['result']['company']
This code returns all devices connected to the network. result is something like this
the result of this code
def scan(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
This is the line which gives an error
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
clents_list = []
for element in answered_list[1:]:
company = vender_finding(element[1].hwsrc)
clent_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc, "vender": company}
clents_list.append(clent_dict)
print(clents_list)
return clents_list
scan('192.168.1.0/24')
but now its return error like this.
In here now a new error starts to occur.
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
This the error that I am getting.
raise ValueError("Unknown network interface %r" % name)
ValueError: Unknown network interface None

By installing the following software issue solved.
1.python 2.7.2 from python.org
2.Microsoft Visual C++ Compiler for Python 2.7 from https://www.microsoft.com/en-us/download/confirmation.aspx?id=44266.
(check this link for more. Microsoft Visual C++ 9.0 is required)
3.pip install scapy==2.4.3rc1 (this is recommended by StackOverflow contributor. this work very well.)
(check these link answer for a recommendation by user Cukic0d. GUID number of windows interface giving error: ValueError: Unknown network interface '{1619EEF1-4D71-4831-87AC-8E5DC3AA516A}')
4.winpcap (to perform scapy sniff() must install this)
Install python 2.7.2 and then install Microsoft Visual C++ Compiler for Python 2.7

You can try "iface" with your network interface.
Ex:
sendp(Ether()/IP(dst="1.2.3.4",ttl=(1,4)), iface="eth1")
More info: https://scapy.readthedocs.io/en/latest/usage.html

Related

OSError: exception: access violation. Yenista Laser instrument on Python

Looking for other similar errors, we have an issue on loading the DLL library supplied with the Yenista laser instrument.
The DLL is correctly loaded while using the python version indicated in the instrument guide (Python 3.4).
Unfortunately, we need Python 3.10 or at least (>3.8) for other instruments.
We have two different files in our folder: CT400_lib.dll and CT400_lib.h (header file).
It looks like that, using this Python version, the DLL functions cause the following error: OSError: exception: access violation reading 0xFFFFFFFFB6E38700
According to the documentation of ctype, it seems that the DLL is resolved differently in the two Python versions.
We have no idea how to use this DLL with the newer Python version. The instrument is old and the company that produces this instrument does not exists anymore.
Our code:
from ctypes import *
dll_ct400 = cdll.LoadLibrary(r"address")
# (we also tried with "dll_ct400 =WinDLL(r"address"))
class Yenista_Control():
[...]
def initYenista(self):
tcError = create_string_buffer(1024)
strRet = create_string_buffer(1024)
iErrorSize = c_int * 1
(iError) = (iErrorSize())
self.uiHandle = c_longlong(dll_ct400.CT400_Init(byref(iError)))
print("{}{}".format("Error/Warning: ", iError[0]))
if self.uiHandle:
strRet = 'OK'
else: strRet = 'Error: could not connect to CT400'
print(strRet)
return strRet
def YenistaLaserSetting(self):
dll_ct400.CT400_SetLaser(self.uiHandle, self.LI_1, self.ENABLE, 10, self.LS_TunicsT100s_HP,
c_double(1530.0), c_double(1570.0), 100)
if self.uiHandle:
strRet = 'OK'
else: strRet = 'Error: could not connect to CT400'
print(strRet)
return strRet
It seems recognizing the "dll_ct400.CT400_Init" in def initYenista, giving the error when trying to access all other functions, as the YenistaLaserSetting reported above.

Mismatched protocol version in packet Error: lost sync or rosserial_python is from different ros release than the rosserial client

I am using a raspberry pi 4 mode B to interface communicate with a Teensy 4.0. I'm using ROS noetic on Ubuntu 20.04. I've flashed the code to the Teensy successfully using platformio. I have a problem, however, when I try and launch the calibration python script for the robot I'm working on. I'm interfacing the raspberry Pi with the Teensy through the GPIO pins (this is after I've flashed the code to the Teensy, I flashed it through usb). When I run the calibration script using roslaunch mini_ros spot_calibration I get the following error:
[servo_calibration-1] process has died [pid 4841, exit code 1, cmd /home/ubuntu/spark_ws/src/spot_mini_mini/mini_ros/src/servo_calibration __name:=servo_calibration __log:=/home/ubuntu/.ros/log/fa068172-32ea-11ec-b45a-513494152363/servo_calibration-1.log].
log file: /home/ubuntu/.ros/log/fa068172-32ea-11ec-b45a-513494152363/servo_calibration-1*.log
[ERROR] [1634874547.846356]: Mismatched protocol version in packet (b'\xf8'): lost sync or rosserial_python is from different ros release than the rosserial client
below is the python code in spot_calibration
#!/usr/bin/env python
"""
DESCRIPTION:
SUBSCRIBERS:
"""
from __future__ import division
import rospy
from mini_ros.srv import CalibServo, CalibServoResponse
from mini_ros.msg import JointPulse
import numpy as np
import sys
import rospkg
rospack = rospkg.RosPack()
sys.path.append(rospack.get_path('mini_ros') + '/../')
sys.path.append('../../')
class ServoCalibrator():
def __init__(self):
rospy.init_node('ServoCalibrator', anonymous=True)
self.serv = rospy.Service('servo_calibrator', CalibServo,
self.calib_service_cb)
self.jp_pub = rospy.Publisher('spot/pulse', JointPulse, queue_size=1)
def calib_service_cb(self, req):
""" Requests a servo to be moved to a certain position
Args: req
Returns: response
"""
try:
jp_msg = JointPulse()
jp_msg.servo_num = req.servo_num
jp_msg.servo_pulse = req.servo_pulse
self.jp_pub.publish(jp_msg)
response = "Servo Command Sent."
except rospy.ROSInterruptException:
response = "FAILED to send Servo Command"
return CalibServoResponse(response)
def main():
""" The main() function. """
srv_calib = ServoCalibrator()
rospy.loginfo(
"Use The servo_calibrator service (Pulse Width Unit is us (nominal ~500-2500))."
)
while not rospy.is_shutdown():
rospy.spin()
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass
The package was supposedly made in ROS Melodic, so that might be why it's throwing the error, but I don't know what to change if the package is melodic exclusive.
The problem is indeed because the roslib package used by rosserial was build for Melodic. As you can guess this error is just caused because of mismatched version ids coming from the arduino side. The best option would be to rebuild ros_lib for Noetic.
To rebuild ros_lib all you have to do is navigate to your sketchbook and run make_libraries.py. Note that this will build up to the currently installed distro, so you need to run this on a machine that has Noetic installed.
cd <sketchbook>/libraries
rm -rf ros_lib
rosrun rosserial_arduino make_libraries.py .
If rebuilding isn't an option you can add the definitions manually. On the arduino side you'll have a ros_lib folder. You have two sub directories you need to change.
The first is ./ros/node_handle.h. At the top of the file you'll see a few protocol versions defined as const uint8_t. Add in the version id for noetic as const uint8_t PROTOCOL_VER6 = 0xfa; then change the line that states what version should be used. const uint8_t PROTOCOL_VER = PROTOCOL_VER6;.
Lastly, you just need to make this same change in ./ros_lib/ros/node_handle.h

How to get DDE server to work in python 3?

In 2015 I have posted a question on SO how to Create DDE server in python and send data continously. The answer and code posted by JayleoPlayGround to that question back then worked flawlessly in python 2.7 and I have used it until recently.
As Python 2 is no longer actively supported from January 2020, I want to move my code to python 3. I have installed pywin32 (version 227) using pip on python 3.7.6 and tried to use the same code as before:
# coded by JayleoPlayGround
# use Portable Python 2.7.5.1 + pywin32-214
import time
import win32ui, dde
from pywin.mfc import object
class DDETopic(object.Object):
def __init__(self, topicName):
self.topic = dde.CreateTopic(topicName)
object.Object.__init__(self, self.topic)
self.items = {}
def setData(self, itemName, value):
try:
self.items[itemName].SetData( str(value) )
except KeyError:
if itemName not in self.items:
self.items[itemName] = dde.CreateStringItem(itemName)
self.topic.AddItem( self.items[itemName] )
self.items[itemName].SetData( str(value) )
ddeServer = dde.CreateServer()
ddeServer.Create('Orbitron')
ddeTopic = DDETopic('Tracking')
ddeServer.AddTopic(ddeTopic)
while True:
yourData = time.ctime() + ' UP0 DN145000001 UMusb DMfm AZ040 EL005 SNNO SATELLITE'
ddeTopic.setData('Tracking', yourData)
win32ui.PumpWaitingMessages(0, -1)
time.sleep(0.1)
When running the above code in python 3.7.6 and using pywin32 (version 227), the external DDE client application that I interface with is able to connect to the DDE server, but the data string is not received correctly. As described before, if I am using Python 2.7 with pywin32 (version 214) this works fine however.
As there are no error messages shown I am lost what the problem is under python 3. I tried all available pywin32 versions for this python version (222 to 227) without success. Any ideas on how to get this to work would be much appreciated.

Alsa Audio library - Error -> Has no PCM member

I'm working on a project where I have to control 8 audio channel.
I'm programming in python3 using alsaaudio library. It all worked but I have these 3 errors and, once I start the program, my internet connection goes down.
In the following code, you can see how I initialize the device (octosound card by AudioInjector). Please note that if the indentitation is wrong is just because a copy paste error.
import alsaaudio
def start_device(ch):
variables.mut.acquire()
if variables.device_flag[ch] == 1:
try:
variables.device_PCM[ch] = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode = alsaaudio.PCM_NORMAL,device=variables.device_name[ch])
variables.device_flag[ch] = 0 # device open
print('device -%s- OPEN' % (variables.device_name[ch]))
except:
print("Except raised")
json_builder.jsonerror("Init device ch" + str(ch) +" FAILED to OPEN",ch)
variables.device_flag[ch] == 1
else:
print("Device -%s- already opened" % (variables.device_name[ch]))
variables.mut.release()
The strange things are that this code works and I can drive all 8 channels but I got 3 errors and my internet stop working:
message: "Module 'alsaaudio' has no 'PCM' member"
message: "Module 'alsaaudio' has no 'PCM_PLAYBACK' member"
message: "Module 'alsaaudio' has no 'PCM_NORMAL' member"
(the device=device_name[ch] works, no error)
Well, I will recommend you to use Alvas.Audio Library which can edit, convert, play, pause convert audio files. The C# Alvas.Audio library can also be used to convert headerless format (SLINEAR) etc.
http://alvas.net/alvas.audio,tips.aspx
Moreover it helps to extract AVI streams and convert one file format to another. So, try the Alvas.Audio C# library and get free trial https://www.filerepairtools.com/alavas-audio-library.html

AttributeError: module 'socket' has no attribute 'AF_PACKET'

I am working on building a packet sniffing program using Python, however I have hit a speed bump. For some reason I think socket has not imported properly, because I am getting the following message when my program is run: AttributeError: module 'socket' has no attribute 'AF_PACKET'
I am using OS X and Pycharm is my IDE and I am running the latest version of Python if that helps.
Anyways here is my complete program so far:
import struct
import textwrap
import socket
def main():
connection = socket.socket(socket.AF_PACKET, socket.SOCKET_RAW, socket.ntohs(3))
while True:
rawData, address = connection.recvfrom(65535)
reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
print('\nEthernet Frame: ')
print('Destination: {}, Source: {}, Protocol: {}'.format(reciever_mac, sender_mac, ethernetProtocol))
# Unpack ethernet frame
def ethernet_frame(data):
reciever_mac, sender_mac, protocol = struct.unpack('! 6s 6s H', data[:14])
return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(socket), data[14:]
# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
bytesString = map('{:02x}'.format, bytesAddress)
macAddress = ':'.join(bytesString).upper()
return macAddress
main()
Thanks for any help in advance!
Actually, AF_PACKET doesn't work on OS X, it works on Linux.
AF_PACKET equivalent under Mac OS X (Darwin)
I ran into this issue on macOS 10.13.1, using Python 3.6.3 and this cool scapy fork that is compatible with python3.
I was using version 0.22 of that tool and as suggested in this issue downgrading to version 0.21 fixed this issue!
In case scapy is not a viable alternative, you could also try the pcap library as suggested in this post (although using python 2 seems to be necessary here).

Categories

Resources