Open connection to remote MySQL using non default (unix) socket - mysql

I'm in a situation where I have to push data to a remote database, from a Powershell script.
The database's server uses multiple instances, each one using a specific socket.
I'm trying to open a connection remotely, using the .Net MySQL connector as follow :
$mdir = Split-Path $script:MyInvocation.MyCommand.Path
[void][system.reflection.Assembly]::LoadFrom("$mdir\MySQL.Data.dll")
$connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$connection.ConnectionString = "host=$myHost;port=$Port;uid=$User;pwd=$Pass;database=$Database;Socket=$Socket;Pooling=False"
$connection.Open()
I'm getting an error saying that Socket is not an existing keyword.
I've found reference to that keyword on google, but indeed not in the official documentation.
Example showing what I want to connect to :
Server : db.domain.com
Port : 2345
Socket : /var/sockets/mycustomsocket.sock
Is there a way to do what I want, and if so, what am I doing wrong ?
EDIT
What I was doing wrong is putting too much trust into the technical knowledge of my client, but at least, I learned something !
The case I described is pure nonsense due to the way MySQL works.
When an instance uses a socket, that socket is bound to a specific port. The case that my client described to me that lead to that question is therefore impossible.
It is not possible to have several instances of MySQL listening on the same port, but using different sockets. Wanting to connect to a remote file socket is therefore a non issue, and you should be able to connect using ip/hostname and port.
The Socket parameter in MySQL is supposed to be used locally, as it was noted in the comments.

Related

can't connect to MySQL remotely on Windows 10 [duplicate]

Sometimes I get the following error while I was doing HttpWebRequest to a WebService. I copied my code below too.
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream()
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = networkCredential(sla);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = v_Timeout * 1000;
if (url.IndexOf("asmx") > 0 && parStartIndex > 0)
{
AppHelper.Logger.Append("#############" + sla.ServiceName);
using (StreamWriter reqWriter = new StreamWriter(request.GetRequestStream()))
{
while (true)
{
int index01 = parList.Length;
int index02 = parList.IndexOf("=");
if (parList.IndexOf("&") > 0)
index01 = parList.IndexOf("&");
string parName = parList.Substring(0, index02);
string parValue = parList.Substring(index02 + 1, index01 - index02 - 1);
reqWriter.Write("{0}={1}", HttpUtility.UrlEncode(parName), HttpUtility.UrlEncode(parValue));
if (index01 == parList.Length)
break;
reqWriter.Write("&");
parList = parList.Substring(index01 + 1);
}
}
}
else
{
request.ContentLength = 0;
}
response = (HttpWebResponse)request.GetResponse();
If this happens always, it literally means that the machine exists but that it has no services listening on the specified port, or there is a firewall stopping you.
If it happens occasionally - you used the word "sometimes" - and retrying succeeds, it is likely because the server has a full 'backlog'.
When you are waiting to be accepted on a listening socket, you are placed in a backlog. This backlog is finite and quite short - values of 1, 2 or 3 are not unusual - and so the OS might be unable to queue your request for the 'accept' to consume.
The backlog is a parameter on the listen function - all languages and platforms have basically the same API in this regard, even the C# one. This parameter is often configurable if you control the server, and is likely read from some settings file or the registry. Investigate how to configure your server.
If you wrote the server, you might have heavy processing in the accept of your socket, and this can be better moved to a separate worker-thread so your accept is always ready to receive connections. There are various architecture choices you can explore that mitigate queuing up clients and processing them sequentially.
Regardless of whether you can increase the server backlog, you do need retry logic in your client code to cope with this issue - as even with a long backlog the server might be receiving lots of other requests on that port at that time.
There is a rare possibility where a NAT router would give this error should its ports for mappings be exhausted. I think we can discard this possibility as too much of a long shot though, since the router has 64K simultaneous connections to the same destination address/port before exhaustion.
The most probable reason is a Firewall.
This article contains a set of reasons, which may be useful to you.
From the article, possible reasons could be:
FTP server settings
Software/Personal Firewall Settings
Multiple Software/Personal Firewalls
Anti-virus Software
LSP Layer
Router Firmware
Computer Turned Off
Computer Not Plugged In
Fiddler
I had the same. It was because the port-number of the web service was changing unexpectedly.
This problem usually happens when you have more than one copy of the project
My project was calling the Web service with a specific port number which I assigned in the Web.Config file of my main project file. As the port number changed unexpectedly, the browser was unable to find the Web service and throwing that error.
I solved this by following the below steps: (Visual Studio 2010)
Go to Properties of the Web service project --> click on Web tab --> In Servers section --> Check Specific port
and then assign the standard port number by which your main project is calling the web service.
I hope this will solve the problem.
Cheers :)
I think, you need to check your proxy settings in "internet options". If you are using proxy/'hide ip' applications, this problem may be occurs.
I had the same problem. The problem is that I didn't start the selenium server. I have downloaded the selenium server and i started it. After starting the selenium server, issue gone and all worked fine.
Refer this : http://coding-issues.blogspot.in/2012/11/no-connection-could-be-made-because.html
I had the same error with my WCF service using Net TCP binding, but resolved after starting the below services in my case.
Net.Pipe.Listener.Adapter
Net.TCP.Listener.Adapter
Net.Tcp Port Sharing Service
In my case, some domains worked, while some did not. Adding a reference to my organization's proxy Url in my web.config fixed the issue.
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="http://proxy.my-org.com/" usesystemdefault="True"/>
</defaultProxy>
</system.net>
When you call service which has only HTTP (ex: http://example.com) and you call HTTPS (ex: https://example.com), you get exactly this error - "No connection could be made because the target machine actively refused it"
I faced same error because when your Server and Client run on same machine the Client need server local ip address not Public ip address to communicate with server you need Public ip address only in case when Server and Client run on separate machine so use Local ip address in client program to connect with server Local ip address can be found using this method.
public static string Getlocalip()
{
try
{
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
return localIPs[7].ToString();
}
catch (Exception)
{
return "null";
}
}
I got this error in an application that uses AppFabric. The clue was getting a DataCacheException in the stack trace. To see if this is the issue for you, run the following PowerShell command:
#("AppFabricCachingService","RemoteRegistry") | % { get-service $_ }
If either of these two services are stopped, then you will get this error.
For me, I wanted to start the mongo in shell (irrelevant of the exact context of the question, but having the same error message before even starting the mongo in shell)
The process 'MongoDB Service' wasn't running in Services
Start cmd as Administrator and type,
net start MongoDB
Just to see MongoDB is up and running just type mongo, in cmd it will give Mongo version details and Mongo Connection URL
Well, I've received this error today on Windows 8 64-bit out of the blue, for the first time, and it turns out my my.ini had been reset, and the bin/mysqld file had been deleted, among other items in the "Program Files/MySQL/MySQL Server 5.6" folder.
To fix it, I had to run the MySQL installer again, installing only the server, and copy a recent version of the my.ini file from "ProgramData/MySQL/MySQL Server 5.6", named my_2014-03-28T15-51-20.ini in my case (don't know how or why that got copied there so recently) back into "Program Files/MySQL/MySQL Server 5.6".
The only change to the system since MySQL worked was the installation of Native Instruments' Traktor 2 and a Traktor Audio 2 sound card, which really shouldn't have caused this problem, and no one else has used the system besides me. If anyone has a clue, it would be kind of you to comment to prevent this for me and anyone else who has encountered this.
For service reference within a solution.
Restart your workstation
Rebuild your solution
Update service reference in WCFclient project
At this point, I received messsage (Windows 7) to allow system access.
Then the service reference was updated properly without errors.
I would like to share this answer I found because the cause of the problem was not the firewall or the process not listening correctly, it was the code sample provided from Microsoft that I used.
https://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx
I implemented this function almost exactly as written, but what happened is I got this error:
2016-01-05 12:00:48,075 [10] ERROR - The error is: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [fe80::caa:745:a1da:e6f1%11]:4080
This code would say the socket is connected, but not under the correct IP address actually needed for proper communication. (Provided by Microsoft)
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);
if(tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
I re-wrote the code to just use the first valid IP it finds. I am only concerned with IPV4 using this, but it works with localhost, 127.0.0.1, and the actually IP address of you network card, where the example provided by Microsoft failed!
private Socket ConnectSocket(string server, int port)
{
Socket s = null;
try
{
// Get host related information.
IPAddress[] ips;
ips = Dns.GetHostAddresses(server);
Socket tempSocket = null;
IPEndPoint ipe = null;
ipe = new IPEndPoint((IPAddress)ips.GetValue(0), port);
tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Platform.Log(LogLevel.Info, "Attempting socket connection to " + ips.GetValue(0).ToString() + " on port " + port.ToString());
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
s.SendTimeout = Coordinate.HL7SendTimeout;
s.ReceiveTimeout = Coordinate.HL7ReceiveTimeout;
}
else
{
return null;
}
return s;
}
catch (Exception e)
{
Platform.Log(LogLevel.Error, "Error creating socket connection to " + server + " on port " + port.ToString());
Platform.Log(LogLevel.Error, "The error is: " + e.ToString());
if (g_NoOutputForThreading == false)
rtbResponse.AppendText("Error creating socket connection to " + server + " on port " + port.ToString());
return null;
}
}
This is really specific, but if you receive this error after trying to connect to a database using mongo, what worked for me was running mongod.exe before running mongo.exe and then the connection worked fine. Hope this helps someone.
One more possibility --
Make sure you're trying to open the same IP address as where you're listening. My server app was listening to the host machine's IP address using IPv6, but the client was attempting to connect on the host machine's IPv4 address.
I've received this error from referencing services located on a WCFHost from my web tier. What worked for me may not apply to everyone, but I'm leaving this answer for those whom it may. The port number for my WCFHost was randomly updated by IIS, I simply had to update the end routes to the svc references in my web config. Problem solved.
In my scenario, I have two applications:
App1
App2
Assumption: App1 should listen to App2's activities on Port 5000
Error: Starting App1 and trying to listen, to a nonexistent ghost town, produces the error
Solution: Start App2 first, then try to listen using App1
Go to your WCF project -
properties ->
->
debuggers
-> unmark the checkbox
Enable Edit and Continue
In my case this was caused by a faulty deployment where a setting in my web.config was not made.
A collegue explained that the IP address in the error message represents the localhost.
When I corrected the web.config I was then using the correct url to make the server calls and it worked.
I thought I would post this in case it might help someone.
Using WampServer 64bit on Windows 7 Home Premium 64bit I encountered this exact problem. After hours and hours of experimentation it became apparent that all that was needed was in my.ini to comment out one line. Then it worked fine.
commented out 1 line
socket=mysql
If you put your old /data/ files in the appropriate location, WampServer will accept all of them except for the /mysql/ folder which it over writes. So then I simply imported a backup of the /mysql/ user data from my prior development environment and ran FLUSH PRIVILEGES in a phpMyAdmin SQL window. Works great. Something must be wrong because things shouldn't be this easy.
I had this issue happening often. I found SQL Server Agent service was not running. Once I started the service manually, it got fixed. Double check if the service is running or not:
Run prompt, type services.msc and hit enter
Find the service name - SQL Server Agent(Instance Name)
If SQL Server Agent is not running, double-click the service to open properties window. Then click on Start button. Hope it will help someone.
I came across this error and took some time to resolve it. In my case I had https and net.tcp configured as IIS bindings on same port. Obviously you can't have two things on the same port. I used netstat -ap tcp command to check whether there is something listening on that port. There was none listening. Removing unnecessary binding (https in my case) solved my issue.
It was a silly issue on my side, I had added a defaultproxy to my web.config in order to intercept traffic in Fiddler, and then forgot to remove it!
There is a service called "SQL Server Browser" that provides SQL Server connection information to clients.
In my case, none of the existing solutions worked because this service was not running. I resumed it and everything went back to working perfectly.
I was facing this issue today. Mine was Asp.Net Core API and it uses Postgresql as the database. We have configured this database as a Docker container. So the first step I did was to check whether I am able to access the database or not. To do that I searched for PgAdmin in the start as I have configured the same. Clicking on the resulted application will redirect you to the http://127.0.0.1:23722/browser/. There you can try access your database on the left menu. For me I was getting an error as in the below image.
Enter the password and try whether you are able to access it or not. For me it was not working. As it is a Docker container, I decided to restart my Docker desktop, to do that right click on the docker icon in the task bar and click restart.
Once after restarting the Docker, I was able to login and see the Database and also the error was gone when I restart the application in Visual Studio.
Hope it helps.
it might be because of authorisation issues; that was the case for me.
If you have for example: [Authorize("WriteAccess")] or [Authorize("ReadAccess")] at the top of your controller functions, try to comment them out.
I just faced this right now...
Here on my end, I have 2 separated Visual Studio solutions (.sln)... opened each one in their own Visual Studio instance.
Solution 2 calls Solution 1 code. The problem was related to the port assigned to Solution 1. I had to change the port on solution 1 to another one and then Solution 2 started working again. So make sure you check the port assigned to your project.
Normally, connection scripts do not mention the port to use. For example:
$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database');
So, to connect with a manager that doesn't use port 3306, you have to specify the port number on the connection request:
$mysqli = mysqli_connect('127.0.0.0.1', 'user', 'password', 'database', '3307');
To check the connections on the MySQL or MariaDB database manager, use the script:
wamp(64)\www\testmysql.php
by putting 'http://localhost/testmysql.php' in the browser address bar having first modified the script according to your parameters.
I forgot to start the service so it failed because no service was listening on port.
Resolved by starting the service.

Connecting R to remote MySQL server - Can't Connect to server

Backstory, I would like to build shiny apps to give to some of our data collectors so they can review what has been collected. We currently house all of our data in a cloud based MySQL server. Ideally, I would like the shiny app to pull data directly from the MySQL server so it can be fully automated without any data pulls and up 24/7.
I have been trying to first just build the connection between R and MySQL using the RMySQL package and can't seem to get it working. I have set up a specific username/password for this connection that is read only(however I have also tried my regular username which has all privileges granted). This is the code I am running;
mydb=dbConnect(
MySQL(),
user='myuser',
password='mypass',
dbname='vgtg',
host='ipaddress',
port=3306,
)
Obviously the 'ipaddress' of the server has been changed for the sake of posting here but it is a generic looking address like
'192.168.1.1'
When I run the code above I get this error message;
Error in .local(drv, ...) :
Failed to connect to database: Error: Can't connect to MySQL server on
'ipaddress' (0)
I have tried looking for previous questions posted but none seem to be exactly this error message that I am receiving. It makes me think that for some reason RMySQL is looking locally for the server when it is actually a cloud based, remote, server.
Also, is there anything more I should set up server side to allow the connection? I do have a server admin to help out but I am not sure how familiar he is with R and likewise I am not particularly familiar with working with servers. He has opened port 3306 for me and is able to see my attempts to connect through the port.
Your syntax is correct with the exception of
port=3306,
You need to drop the comma. That said, the error you received is unrelated to the syntax.
Without knowing the details of your setup, it is hard to diagnose. Where does the MySQL DB reside? For example, if it is on an AWS RDS instance, then the host isn't a standard IP address, it is something like this
mydb.cm1abc2v4mod.us-west-1.rds.amazonaws.com
Assuming that the IP address you used is correct, then the problem is most likely on the server. You need to ensure that port 3306 is open to traffic. Otherwise, R will not be able to connect to the DB.

MySql.Data.MySqlClient.MySqlException using ServiceStack ORMLite

I am working with ServiceStack evaluating the ORMLite provider with MySql for use on a.NET Core 1.1 project. I am running into a curious issue I am not sure what the problem is and looking for some guidance on how to troubleshoot this further or possible fixes.
I am running the .Net Core app in a standard docker container and MySql in the standard MySql container. I have been able to successfully run MySQL and connect with the workbench tool.
What I cannot do is get the executing code of the web application to successfully connect to the MySQL container. I have tried various combinations. Those where the IP Address or hostname were wrong I received a meaningful error saying the host was unknown.
But under scenarios where server name or IP address values that are used that are appropriate for the MySQL container, I receive a generic MySQLException error. The username and password are correct. I have even used the root account to ensure that there aren't any potential security hangups.
Here is a code snippet of where I am attempting to connect. This setup was working well using a local SQL db file, there is just something I am missing with either the configuration of Docker or MySQL that I haven't been able to isolate.
const string connectionString = "Server=3400f112c973:3306;Database=ServiceDB;Uid=root;Pwd=my-secret-pw;";
container.Register<IDbConnectionFactory>(
new OrmLiteConnectionFactory(connectionString, MySqlDialect.Provider ));
using (var db = container.Resolve<IDbConnectionFactory>().Open())
{
if (db.CreateTableIfNotExists<TypeExample>())
{
//Add seed data
}
}
I have figured out my scenario.
In the MySQL Connection string, if you are using a non-standard port, you need to use the port parameter to specify the different port and omit the port entirely if using the standard port.
My issue was I was always using "Server=servername:port;" which is an incorrect format and should have been "Server=servername;Port=port;" in the cases where I was using a nonstandard port number, otherwise Port= can be omitted.

mysql_connect: IP Address or Localhost?

I saw the following statement on StackOverflow and was wondering about its meaning:
If you connect via 'localhost', the connection will automatically be established via the MySQL socket, which is really cheap anyways.
The discussion thread was pretty old, so I didn't want to comment on it.
Basically what I understand is, that using 'localhost' when connecting to your mysql database has certain advantages - such as "automatically established connections via MySQL socket". What does that mean exactly?
Currently I'm using
mysql_connect("73.21.24.201", [...]);
(changed to a random IP Address)
Does it make any difference? Can I change it to "localhost" without having to worry about it? (The mysql server is obviously on the same server/ip address as my website/application)
When you connect to 'localhost' you'll connect using a Unix socket, which is just a communications channel for the local processes to use. The big advantage of this is that you can disable networking completely in MySQL, and negate any processing overhead and security risks that go along with that.
When MySQL starts, it creates a socket file (typically at a place like /var/lib/mysql/mysql.sock) that your client program needs to be able to find. On a typical PHP (you didn't say, but I'm assuming) setup, it should know where to find this socket. If not, check /etc/my.cnf and /etc/php.ini to make sure the values match.
And finally, if that is PHP, stop using mysql_*() functions in PHP right now! They have been deprecated for years and are inefficient and insecure.

Connecting to SQL process with Zend

I'm trying to connect my Zend application to a MySQL process running on a shared server. The basic config should be fine, as it was working with a LAMP server.
The problem is, I need to specify the host as being the an sql process: myprocess.db, rather than localhost:
resources.db.adapter = PDO_MYSQL
resources.db.params.charset = "utf8"
resources.db.params.host = mysqlprocess.db
resources.db.params.username = username
resources.db.params.password = password
resources.db.params.dbname = dbname
However, when I do, I get this:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]:
Can't connect to local MySQL server through socket 'please_see_the_faq' (2)
in /f5/metamusic/protected/application/controllers/SearchController.php on line 418
The host I'm using is NearlyFreeSpeech, and this message is apparently triggered when attempting to connect to SQL without specifying the process you're interested in:
http://faq.nearlyfreespeech.net/section/mysql/mysqllocalhost#mysqllocalhost
Using the same details and mysql_connect($server, $user) works without issue, so it looks like Zend is somehow not using the correct host parameter.
Any ideas what's going wrong? Any help would be much appreciated.
try using
resources.db.params.host = myprocess.db
The host in the db config has to point to a database server. localhost or 127.0.0.1 are references for the database being on the same server as the application. In a hosting environment you usually have the server on a remote server so the host has to be either an IP address or a DNS name for the host.
Check the second question in the FAQ.
Update
My bad, that is about DSN and not DNS. Still, that's where the problem is. The resources.db.params.host directive in the config expects a reference to the database server and myprocess.db is neither a DNS name nor a IP address. You probably need localhost for that but then you will still be missing the DSN. I currently don't see how you set a DSN in PHP for MySQL and therefore Zend. Have a further look at this MYSQL DSN.
Update 2
You are correct with the socket and that this is related. I think the problem is the Zend PDO_MYSQL adapter. Zend funnels this directly to PDO(). There are this additional config options I mentioned above (MYSQL DSN) which is missing in the Zend implementation. Although the PDO_MYSQL adapter overrides the connect() method it does not look for this options.
However, there is another adapter mysqli which connects directly to MySQL and actually the same way as your test with mysql_connect(). It uses mysqli_real_connect() instead and that connection might understand the process name for the socket. So, you can try the following in your config:
resources.db.adapter = "mysqli"
I'm posting my eventual solution here for future reference:
It turns out, the database connection was already working. However, my call to mysql_real_escape_string() was failing, and the resulting error message suggested that the entire database connection had failed.
The solution was simply to replace the above call with Zend_DB_Adapter's quote(), and suddenly everything works.
Why this works on a LAMP machine and not a shared server, I have no idea. For now though, this is a good enough solution!