I am trying to connect my laptop(as client) to my android phone(as listener) using python-bluez on the laptop and android-bluetooth API on the phone.
I use the following code for my phone:
BluetoothServerSocket tmp = badapter.listenUsingRfcommWithServiceRecord(
badapter.getName(), MY_UUID);
BluetoothServerSocket bserversocket = tmp;
if(bserversocket != null)
{
BluetoothSocket acceptsocket = bserversocket.accept(timeout);
}
//timeout is set to about 15 sec
if(acceptsocket != null)
{
out.append("got the connection...\n");
}
and the following in python for my laptop client:
from bluetooth import *
btooth_addr = "38:EC:E4:57:1F:1B"
sock = BluetoothSocket(RFCOMM)
sock.connect((btooth_addr, 2))
print "Connected"
sock.close()
the listener time-outs without acknowledging any connections from the laptop, while the sender moves on to print 'Connected' on all attempts on different ports.
the problem is that I don't know and can't set the port/channel the android phone is listening on, and also that I am required to fill in a port number as second argument of 'connect'(2 in this snippet).
please help me out - my sole goal at this time is to get the connection attempt acknowledged by the phone.
Have a look at the pybluez documentation(source code) for establishing client connections.
You can get the correct port for the supplied Bluetooth address and UUID using find_service.
Then connect your socket just as you do in your code, replacing hardcoded port value with the correct one.
Don't forget to vote up!
Related
I'm new to Dart and Flutter. I know a bit about Sockets. Here is my question:
I tried to create a TCP socket on a emulator with flutter (on android emulator Pixel 3A API 33) and connect it with another emulator(identical but diffrent emulator, Pixel 3A API 33). I got en error it says "Connection Refused (OS Error: Connection refused, errno = 111),address = 0.0.0.0, port = 36802)
I'm trying to make p2p chat application using flutter. I'm creating a socket in here in p1:
myPort = 43761;
String mysocketIP = "0.0.0.0";
final Future<ServerSocket> mySocket = ServerSocket.bind(mysocketIP, myPort);
and listening the socket like this in p1:
mySocket.then((ServerSocket listenSocket) {
listenSocket.listen((Socket mysocket) {
mysocket.listen((Uint8List data) async {
String mysocketResponse = String.fromCharCodes(data);
String strData = utf8.decode(data);
if(mysocketResponse == "///initiate"){
p2pSocket.add(utf8.encode("Got you message"));
}
print(strData);
});
});
});
All code in p1 about socket is given.
And here comes p2, which is client. Trying to connect to p1:
(I'm getting relevant port and ip from a server. That part works fine, I tested. serverResponse is the response from server. recKey means reciever's key. Its not relevant to my problem. Just another stuff.
code comes to else if block and executes but in Socket.connect line it blows.
late String recieverClientIP;
late int recieverClientPORT;
/*
...
...
*/
else if(serverResponse.length>=8 && serverResponse.substring(0,8)=="//recKey") {
targetsKey = serverResponse.substring(8);
// p2p sohbeti baslatıyoruz.
p2pSocket = await Socket.connect(recieverClientIP, recieverClientPORT);
//p2pSocket.write("///initiate");
}
;
Here is the erros message I get:
ERROR MESSAGE
I realized that in error, it says another port number. I'm using (IP 0.0.0.0) port number 47761 in p1 and in error it says another port number. Maybe it about it? I don't know I'm so confused.
By the way I'm using Android Stuido. With Emulator. Emulator I'm using is Pixel 3A API 33 x86 64
EDÄ°T: I'm using 10.2.2.2 in Server, 0.0.0.0 in p1. I can not create a socket with 10.0.2.2 in p1 it gives error. That's why I'm using 0.0.0.0 it's working.
Thanks in advance.
I can able to fetch all device ip addresses in Local Area Network with inetaddress class. What I need to do is reverse lookup ip-address and find as device name in network like : "Jimmie's Macbook"
My Code block which able to fetch all IP address over Local Network Range:
private ArrayList<String> scanSubNet(String subnet) {
ArrayList<String> hosts = new ArrayList<>();
InetAddress inetAddress;
for (int i = 1; i <= 255; i++) {
try {
inetAddress = InetAddress.getByName(subnet + String.valueOf(i));
if (inetAddress.isReachable(1000)) {
hosts.add(inetAddress.getHostName());
Log.d(TAG, InetAddress.getByAddress(inetAddress.getAddress()).getHostAddress());
Log.d(TAG, InetAddress.getByAddress(inetAddress.getAddress()).getCanonicalHostName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return hosts;
}
And i am calling my method as;
ArrayList<String> subnetList = scanSubNet("192.168.1.");ArrayList<String> subnetList = scanSubNet("192.168.1.");
in Log.d(TAG, i am trying to get device name with reverse dns. But both of line gives me output as ip-address ( Not Device-Name as string)
Is there any chance to succeed it ?
Regards,
Onder.
I just do it with fetching MACID and match first 3digits which belongs manufacturers.
https://macvendors.com/ this website also provide api (Post/GET) to resolve MAC Address.
Instead of resolve fullname of MAC, you need to do Handshake peer to peer.
This is probably happening due to router misconfiguration.
Within a LAN, there are no crucial functions that depend on successful reverse DNS lookups, so a misconfiguration of that kind can easily go undetected for a long time.
It is kind of hard to tell what is wrong in your particular case without a lot more information about your LAN, but the first thing that comes to mind is configuring a proper "DNS Suffix" on the router. This is usually found under DHCP settings.
i am using PJSIP for voice calling. When i used our server, everything fine i.e. call connected, communicate. But when i am using SIP2SIP.INFO server. Registration is OK But Call is not connected. i saw log in SIP2SIP.info there wasn't log of outgoing or incoming call.
so call is not initiate.
char cfg_reg_uri[] = "sip:sip2sip.info";
char cfg_cred_realm[] = "sip2sip.info";
char cfg_cred_scheme[]="digest";
pjsua_acc_config cfg;
pjsua_acc_config_default(&cfg);
cfg.id = pj_str(cfg_id);
cfg.reg_uri = pj_str(cfg_reg_uri);
cfg.cred_count = 1;
cfg.cred_info[0].realm = pj_str(cfg_cred_realm);
cfg.cred_info[0].scheme = pj_str(cfg_cred_scheme);
cfg.cred_info[0].username = pj_str(cfg_cred_username);
cfg.cred_info[0].data_type = PJSIP_CRED_DATA_PLAIN_PASSWD;
cfg.cred_info[0].data = pj_str(cfg_cred_password);
status = pjsua_acc_add(&cfg, PJ_TRUE, &_acc_id);
I noted that we need to use outbound proxy in sip2sip called "proxy.sipthor.net".
but confused how can i used in pjsip code.
please help expert.
If you read the Sip2Sip device configuration page it states that:
" the SIP device must always perform DNS lookups as defined in SIP standard RFC3263 (NAPTR + SRV + A DNS lookups)"
PJSIP supports DNS SRV lookups.
In PJSUA it will only do DNS SRV lookup if you don't provide the port number in the SIP URL.
"sip:xxx#sip2sip.info" will try to do a DNS SRV record lookup first then fail over to DNS A/C name lookup.
and
"sip:xxx#sip2sip.info:5060" will only do DNS A/C name lookup.
What PJSUA will not support automatically is failover support, they say:
"What we've been suggesting is to implement the failover mechanism in the application layer."
If you want a "quick and easy" setup, what you want to do is set the outbound_proxy to "proxy.sipthor.net". e.g.
cfg.outbound_proxy_cnt = 1;
cfg.outbound_proxy[0] = pj_str("sip:proxy.sipthor.net:5060");
If you want a more robust solution, you need to use pjsip's SRV resolution functions to resolve sip2sip.info srv record e.g: "_sip._udp.sip2sip.info" and then set the outbound_proxy records with the result.
The code is a little bit involved.
pjsip_resolver_t* resolver_;
...
status = pjsip_resolver_create( pool, &resolver_ );
...
pjsip_host_info host;
host.flag = PJSIP_TRANSPORT_DATAGRAM; // is using UDP, see pjsip_transport_flags_e
host.type = PJSIP_TRANSPORT_UDP; // if using UDP, see pjsip_transport_type_e
host.addr.host = pj_str("sip2sip.info");
host.addr.port = 5060;
pjsip_resolve(resolver_, pool, &host, token, resolver_cb_func);
...
static void resolver_cb_func( pj_status_t status, void *token, const struct pjsip_server_addresses *addr)
{
...
// use results to fill in the outbound_proxy
}
You could also take it further to support failover, but it looks like sip2sip doesn't have multiple sip servers in there DNS SRV record so it will not be used currently. If they ever add more then it would become more useful.
_sip._udp.sip2sip.info
Server: fritz.box Address: fd00::2665:11ff:fef9:ec51
Non-authoritative answer:
_sip._udp.sip2sip.info SRV service location:
priority = 100
weight = 100
port = 5060
svr hostname = proxy.sipthor.net
sip2sip.info nameserver = ns2.dns-hosting.info
sip2sip.info nameserver = ns1.dns-hosting.info
sip2sip.info nameserver = ns7.dns-hosting.info
Sip2Sip also support STUN setup, so I would also setup the STUN settings on the account as well:
cfg.stun_srv_cnt = 1;
cfg.stun_srv[0] = pj_str("sip2sip.info");
Since your example seems to not provide the port information it should work. To diagnose this further would require see the pjsip log output.
Why Socket can be open on the android emulator and connect to the python server code and open a socket !! In other Hand When i run same android code on the mobile it doesn't run . didnt open a socket ..Any suggestion what is the problem and how to solve such thing
enter code here
import sys
from threading import Thread
import socket
import MySQLdb
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(2048)
print rm
i=0
while (i<2):
if (rm) == row[i][0]:
reply="\n Welcome to our game %s: %s"%(rm,row[i][1])
self.sockfd.send(reply)
break
else:
i=i+1
if i==2:
reply="\n Error opaa ba2a"
self.sockfd.send(reply)
i=0
break
break
except ValueError:
self.sockfd.send("\n UNVAlied Comment ")
def run(self):
self.newClientConnect()
while True:
buff = self.sockfd.recv(2048)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '50.0.10.107'
PORT = 5807
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
print ("Server Started")
try:
serversocket.bind(('',54633))
except ValueError,e:
print e
serversocket.listen(5)
db= MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="new_schema")
x=db.cursor()
x.execute("SELECT * FROM lolo")
row = x.fetchall()
print "Connected to the Database"
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
The python code and the server code it map and button when click on button connection start and it work great on the emulator
Could be a number of thing:
You don't have networking permissions enabled in your manifest file
Your wifi / 3G is disabled
If your server is on your personal computer and you're connected to the internet using a router then you need to redirect the port you're using for socket communication from the router to your machine.
If your code works on emulator but not on real phone, that could be a network issue. Emulator depends on LAN to access your server and phone access through 3G network. Is your server accessible through internet?
I am new to both Android and Java so I beg your pardon if my question
is asked at the inappropriate group or forum. I made a .Net
application for my company and recently they asked me to port it on
Android so as to install it on Samsung Galaxy Tabs.
First of all, I am using Eclipse, JDK 6, target platform android 2.2
and an Emulator with the GalaxyTab plugin. My operating system is Windows 7.
This application, sends and receives messages to and from a certain
controller on the network using UDP.
In short my application uses a "DatagramSocket", binds it to a local
"InetSocketAddress" and then launches a thread that listens for
datagrams, while another thread sends requests to the controller upon
the user's request. Here is a some code snippet:
This is where I assign the local address and the socket:
try {
loc_addr = new InetSocketAddress(
Inet4Address.getByAddress(
new byte[]{(byte) 192,(byte) 168,1,(byte)240}), 0xBAC0);
//192.168.1.240 is the IP of my machine on the network
} catch (UnknownHostException e) {
.......
}
try {
soc = new DatagramSocket();
soc.setReuseAddress(true);
soc.setBroadcast(true);
soc.bind(loc_addr);
} catch (SocketException e) {
.......
}
This is where I listen for incoming datagrams:
try{
buf = new byte[1024];
receive_pac = new DatagramPacket(buf, 1024);
soc.receive(receive_pac);
if (receive_pac.getData() != null){
.......
}
}
This is where I send data:
try {
addr = (Inet4Address) Inet4Address.getByAddress (new byte[]
{(byte) 192,(byte) 168,1,(byte) 255}); //The message I am sending should be broadcasted
} catch (UnknownHostException e) {
......
}
sendPacket = new DatagramPacket(buf, buf.length, addr,
loc_addr.getPort());
try {
soc.send(sendPacket);
} catch (IOException e) {
......
}
Well when I use "soc.bind(...)" I receive the following exception:
cannot assign requested address
Then I receive a debug message (I don't know if it is relevant):
DEBUG/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
The application is working, I verified through "WireShark" that when I
ask from the emulator to send the data to the controller, the
controller replies back with the expected data correctly. However, the
socket, in the application, on the emulator doesn't receive anything and stays blocked on
the "Receive" call!
Can anyone help me figure out what problem or error I have committed with the receiving part of my application!
Any help is much appreciated,
TMI,
[Edited: If you saw my other answer, please disregard, I made the classic mistake of changing two variables in one test and it was the other variable that made the difference.]
In regards to this:
I tried binding it to the socket and it resulted with the "SocketException: Invalid Argument". Still the program delivered the same operation! Do you have any idea what this exception might mean?
You may have solved this by now, but I just had the same question and answered it myself here.
What got rid of this exception for me was to change the way I was creating the DatagramSocket.
From:
sock = new DatagramSocket();
To:
DatagramChannel channel = DatagramChannel.open();
DatagramSocket socket = channel.socket();
Usually you see that error message if you're trying to bind to an IP address that you don't own. Are you sure that the IP address of your Android emulator is 192.168.1.240? The emulator IP can be different from your host machine IP.